jQuery模板插件:如何创建双向绑定?

And*_*rey 2 javascript data-binding jquery two-way jquery-templates

我开始使用jQuery模板插件(微软创建的那个),但现在我遇到了这个问题:模板是针对一堆绑定到对象数组的表单; 当我在其中一个表单上更改某些内容时,我希望绑定的对象更新,我无法弄清楚如何自动化它.

这是一个简单的例子(现实生活中的模板和对象要复杂得多):

<!-- Template -->
<script type="text/html" id="tmplTest">
    <input type="text" value="${textvalue}"/>
</script>

<!-- object to bind -->
<script type="text/javascript">
    var obj = [{textvalue : "text1"},{textvalue : "text2"}]

    jQuery("#tmplTest").tmpl(obj)
</script>
Run Code Online (Sandbox Code Playgroud)

这将填充两个文本框,每个文本框都绑定到来自相应对象的值.现在,如果我更改其中一个文本框中的值,我需要更新相应的数据对象的值.知道怎么做吗?

Ser*_*los 9

jQuery模板实际上并没有实现双向数据绑定,但是另一个微软开发的jQuery插件呢.这篇Scott Guthrie帖子实际上涵盖了tmpl插件和数据链接插件.向下滚动到"支持客户端数据链接",Scott详细介绍了数据链接插件的工作原理.

但是,对于双向数据绑定,我发现knockoutjs扩展更好更清晰.该声明的语法保持标记清洁和自定义数据绑定覆盖允许多种应用.最后,映射插件非常适合将JSON从服务器处理为绑定.最后,knockoutjs也有基于tmpl插件的绑定.

祝你好运.

编辑:更新的代码示例

需要的脚本:

<script src="/Scripts/jquery-1.5.0.min.js" type="text/javascript"></script>    
<script src="/Scripts/jquery.tmpl.js" type="text/javascript"></script> 
<script src="/Scripts/knockout.js" type="text/javascript"></script>      
<script src="/Scripts/knockout.mapping.js" type="text/javascript"></script>    
Run Code Online (Sandbox Code Playgroud)

然后是肉和土豆

<!-- div for loading the template -->
<div data-bind='template: { name: "tmplTest", foreach: viewModel.list }'>    
</div>

<!-- your template -->
<script type='text/html' id='tmplTest'>
    <div>        
        <span data-bind='text: textvalue, uniqueName: true'></span>
        <input data-bind='value: textvalue, uniqueName: true, valueUpdate:"afterkeydown"'/>
    </div>
</script>

<script type='text/javascript'>
       var viewModel = ko.mapping.fromJS(
        {            
            list:[  { textvalue: "text1" },
                    { textvalue: "text2"}   ]
                }); 

        $(function() {
            ko.applyBindings(viewModel);
        });
 </script>
Run Code Online (Sandbox Code Playgroud)