0

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.

1
  • Please add your relevant code here, no external links to the actual problem pls
    – Ja͢ck
    May 28, 2012 at 13:21

1 Answer 1

0

Actually, the problem is reproducible in a simple example without the jQueryUI bindings. The problem has to do with the $data keyword inside of knockout templates.

Apparently $data cannot be used for a two-way binding inside of a template. See this Google Groups thread for some commentary:

If you have items: ["one", "two", "three"] or even [ko.observable("one"), ko.observable("two"), ko.observable("three")] within a foreach $data will be the raw value and KO has no way at that point to know how to write back to it. You need to use objects with properties, in the case that you need to read/write access to the value.

So one way to get around this limitation is to create a simple ViewModel for your date objects:

var DateViewModel = function (initialValue) {
    this.value = ko.observable(initialValue);
};

And then in your main ViewModel you could write:

var ViewModel = function() {
    this.dates = ko.observableArray([
        new DateViewModel("from"),
        new DateViewModel("to")
    ]);
};

And your template would end up being something like this:

<script type="text/html" id="datepicker-template">
    <span data-bind="text: value"></span>
    <input type="text" data-bind="value: value">
</script>

Example: http://jsfiddle.net/RjEnh/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.