I have got this templated knockout-loop:
<div id="accordion" data-bind="jqAccordion:{},template: {name: 'task-template',foreach: Tasks,afteradd: function(elem){$(elem).trigger('valueChanged');}}">. </div>
<script type="text/html" id="task-template">
<div data-bind="attr: {'id': 'Task' + TaskId}" class="group">
<h3><b><input name="TaskName" data-bind="value: TaskName /></b></h3>
<p>
Due Date: <input class="datepicker" data-bind="myDatepicker : {}, value: taskDueDate" />
</p>
</div>
</script>
Where datepicker is a jQuery Ui datepicker function:
ko.bindinghandler.myDatepicker = $(function() {
init: function( element, valueAccessor) {
$(element).datepicker({
changeMonth: true,
changeYear: true
});
}),
etc.
}
why does this not work?
Symptoms are: the calender is showing and the widget respond to my interactions but no date is returned to the input-field. Any clues?
Thank you in advance!
You need to bind some viewModel attribute to the datepicker binding... You're overthinking that part.
But you do need to do some special handling for when the datepicker changes the element's value because it will otherwise mess up the way knockout normally intercepts the change.
Set up the binding like this...
HTML:
<div id="accordion" data-bind="jqAccordion:{},template: {name: 'task-template',foreach: Tasks,afteradd: function(elem){$(elem).trigger('valueChanged');}}">. </div>
<script type="text/html" id="task-template">
<div data-bind="attr: {'id': 'Task' + TaskId}" class="group">
<h3><b><input name="TaskName" data-bind="value: TaskName /></b></h3>
<p>
Due Date: <input class="datepicker" data-bind="myDatepicker : taskDueDate" />
</p>
</div>
</script>
And the handler like so:
ko.bindingHandlers.myDatepicker = {
init: function(element, valueAccessor) {
var unwrappedObs = valueAccessor();
$(element).val(ko.unwrap(unwrappedObs));
$(element).datepicker({
changeMonth: true,
changeYear: true
});
ko.utils.registerEventHandler(element, "change", function () {
var unwrappedObs = valueAccessor(),
val = $(element).datepicker("getDate");
unwrappedObs(val);
});
}
};
Here's a fiddle: http://jsfiddle.net/brettwgreen/nmb6c6gq/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With