When using jquery-ui custom bindings to add a datepicker to a text field it only updates my model when I don’t use templates.
Simple JSFiddle demostration of problem
HTML:
<script type="text/html" id="datepicker-template">
<span data-bind="text: $data"></span>
<input type="text" data-bind="jqueryui: {widget:'datepicker'}, value: $data">
</script>
<h2>Witout templates</h2>
<div>
<span data-bind="text: from"></span>
<input type="text" data-bind="jqueryui: {widget:'datepicker'}, value: from">
<span data-bind="text: to"></span>
<input type="text" data-bind="jqueryui: {widget:'datepicker'}, value: to">
</div>
<h2>With template<h2>
<div data-bind="template: {name:'datepicker-template', foreach: dates}"></div>
JavaScript:
$(function(){
var ViewModel = function(){
this.from = ko.observable("from");
this.to = ko.observable("to");
this.dates = ko.observableArray([this.from, this.to]);
};
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
});
Feel like I’m missing something very simple.
Actually, the problem is reproducible in a simple example without the jQueryUI bindings. The problem has to do with the
$datakeyword inside of knockout templates.Apparently
$datacannot be used for a two-way binding inside of a template. See this Google Groups thread for some commentary:So one way to get around this limitation is to create a simple ViewModel for your date objects:
And then in your main ViewModel you could write:
And your template would end up being something like this:
Example: http://jsfiddle.net/RjEnh/