敲除模板中的jQuery UI小部件绑定

时间:2012-05-28 13:11:17

标签: jquery-ui knockout.js

使用jquery-ui custom bindings将日期选择器添加到文本字段时,只有在我不使用模板时才更新我的模型。

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);
});​

感觉我错过了很简单的事情。

1 个答案:

答案 0 :(得分:0)

实际上,在没有jQueryUI绑定的简单示例中,问题是可重现的。问题与淘汰模板中的$data关键字有关。

显然$data不能用于模板内部的双向绑定。见this Google Groups thread for some commentary

  

如果您有物品:[“one”,“two”,“three”]或甚至   [ko.observable(“one”),ko.observable(“two”),ko.observable(“three”)]   在一个foreach $ data中将是原始值,而 KO无从   那点知道如何回写它。你需要使用对象   具有属性,在您需要读/写访问权限的情况下   价值。

因此,解决此限制的一种方法是为日期对象创建一个简单的ViewModel:

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

然后在你的主ViewModel中你可以写:

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

你的模板最终会是这样的:

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

示例: http://jsfiddle.net/RjEnh/