executing kendoDatePicker on element in a partial view with knockout

226 Views Asked by At

So I'm working on binding data with elements by knockout. Then a have a partial view that renders when I click a button. Everything is working just fine so far, I get the right data I need to the partial. The problem is that i have an input that I want to act like a kendoDatePicker but it wont. I've notice that when I click the button to render the Partial view, it execute the right method and gets the right data but in the same method it does $("#id").kendoDatePicker(); But the DOM element is not yet rendered and I guess that is the problem. I've tried to knockout-bind the element like: <input data-bind="kendoDatePicker: {value: startDate}"/> but then not even the date is there. Notice the the main div in the partial view is binded like this <div data-bind="with: $root.shift"> <input id="randomId" data-bind: Start"/> //thats not showing in the main DOM until I the partial is loaded</div> when i remove the "with" binder the i see all the element inside this parital but I lose the functionality of the button.

Anyone got the same problem? Is there anything I do/change to make it work?

1

There are 1 best solutions below

1
On BEST ANSWER

You're right that not having the element in the DOM is the problem. Note that knockout is responsible for handling the DOM changes so trying to grab elements and doing something with them outside knockout is not a good practice.

Instead, use knockout custom bindings. They allow you to create a custom binding that operates on the DOM elements with respect to knockout and how he handles them. Therefore:

ko.bindingHandlers.kendoDatePicker = {
    init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
      //here you can access (and possibly pass it to the options) the 'value' by callnig valueAccessor().   
      $(element).kendoDatePicker();
    }
};

ko.applyBindings({});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="http://kendo.cdn.telerik.com/2017.1.118/js/kendo.all.min.js"></script>
 <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2017.1.118/styles/kendo.common.min.css" />

<input id="datepicker" value="10/10/2011" style="width: 100%" data-bind="kendoDatePicker: {value: 'somevalue'}" />