JQuery Tmpl 和数据绑定一起工作
我正在尝试让数据绑定和 tmpls - jquery 插件能够很好地协同工作。因此,我想使用模板来呈现数据,然后使用数据绑定将其挂回到我的对象中。例如:
var items = [{ Name: 'Barak Obama', Phone: '555-1212' },
{ Name: 'George Bush', Phone: '444-2222'}];
function addItems() {
$("MyList").html("");
for (var index in items) {
$("#ListTmpl").tmpl(items[index]).link(items[index]).appendTo("#MyList");
}
};
使用这样的模板:
<script id="ListTmpl" type="text/x-jquery-tmpl">
<li>
<input id="Name" value="${Name}" />
<input id="Phone" value="${Phone}" />
</li>
</script>
但是,我遇到的问题是我希望项目包含一个数组,并使用 {{each}}
var items = [{ Name: 'Barak Obama', Phone: '555-1212',
kids: [{Name: "Malia"}, {Name: "Sasha"}] },
{ Name: 'George Bush', Phone: '444-2222'},
kids: [{Name: "Barbara"}, {Name: "Jenna"}] }];
和这样的模板进行渲染:
<script id="ListTmpl" type="text/x-jquery-tmpl">
<li>
<input id="Name" value="${Name}" />
<input id="Phone" value="${Phone}" />
<ul>
{{each kids}}
<li> ${Name}
{{/each}}
</ul>
但是我如何获取孩子的姓名数据链接回原始对象?
I am trying to get data binding and tmpls - the jquery plugins to work together well. So I want to use a template to render the data, and then data binding to hook it back into my objects. For example:
var items = [{ Name: 'Barak Obama', Phone: '555-1212' },
{ Name: 'George Bush', Phone: '444-2222'}];
function addItems() {
$("MyList").html("");
for (var index in items) {
$("#ListTmpl").tmpl(items[index]).link(items[index]).appendTo("#MyList");
}
};
With the template like this:
<script id="ListTmpl" type="text/x-jquery-tmpl">
<li>
<input id="Name" value="${Name}" />
<input id="Phone" value="${Phone}" />
</li>
</script>
However, where I have a problem is that I want item to contain an array, and render than with {{each}}
var items = [{ Name: 'Barak Obama', Phone: '555-1212',
kids: [{Name: "Malia"}, {Name: "Sasha"}] },
{ Name: 'George Bush', Phone: '444-2222'},
kids: [{Name: "Barbara"}, {Name: "Jenna"}] }];
and a template like this:
<script id="ListTmpl" type="text/x-jquery-tmpl">
<li>
<input id="Name" value="${Name}" />
<input id="Phone" value="${Phone}" />
<ul>
{{each kids}}
<li> ${Name}
{{/each}}
</ul>
But how do I get the kids names data linked back to the original objects?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能想查看 knockout.js
它确实使用 jquery 模板和它自己的绑定机制。
You might want to look at knockout.js
It does use jquery templates and it's own binding mechanism.
.link() 目前不支持您正在寻找的嵌套数组或对象。您很可能希望展平 JSON 对象以利用数据链接: http://jsfiddle.net/rUrXF /1/
看起来嵌套对象存在一个问题:https: //github.com/jquery/jquery-datalink/issues/24
.link() doesn't currently support nested arrays or objects like you are looking for. You will most likely want to flatten out your JSON object to take advantage of datalinking: http://jsfiddle.net/rUrXF/1/
It looks like there is an issue open for nested objects: https://github.com/jquery/jquery-datalink/issues/24