映射:foreach绑定仅在第一次工作 [英] Mapping: foreach binding work only the first time
问题描述
我在HTML文件中包含以下代码段 JQuery :
I have the following snippet JQuery inside an HTML file:
$.getJSON("/events/", function (data) {
viewModel = ko.mapping.fromJS(data);
ko.applyBindings(viewModel);
});
例如,当用户按下按钮并返回JSON时,将执行代码:
The code is executed when, for example, the user presses a button and returns JSON like:
{"Events":[{"Name":"Event1"},{"Name":"Event2"},{"Name":"Event3"}]}
此结果链接到(使用 KnockoutJS ):
This result is linked (using KnockoutJS) to:
<ul data-bind="foreach: Events">
<li><span data-bind="text: Name"></span></li>
</ul>
对于$.GetJSON
的第一次调用,一切正常.我得到了我想要的,即(浏览器输出):
Everything works fine with the first call to $.GetJSON
. I get what I want, which is (browser output):
- Event1
- Event2
- Event3
- Event1
- Event2
- Event3
但是在随后的"$.GetJSON"调用中,在 Firebug 中出现以下错误:
But in subsequent calls to "$. GetJSON" I get the following error in Firebug:
containerNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling); containerNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling); 我没有列表项. 我做错了什么? 非常感谢您. Knockout的重点是处理视图和视图模型之间的交互.在这种情况下,您尝试更新事件列表以响应按钮单击.单击按钮应链接到视图模型中的函数,而列表应链接到单击按钮时更新的可观察数组.我在这里把它们放在一起: http://jsfiddle.net/mbest/uZb3e/以及重要部分如下: The whole point of Knockout is to handle the interaction between your view and view model. In this case, you're trying to update a list of events in response to a button click. The button click should be linked to a function in your view model, while the list should be linked to an observable array that's updated when you click the button. I've put this together in a fiddle here: http://jsfiddle.net/mbest/uZb3e/ and the important parts are below: JavaScript: Javascript: 这篇关于映射:foreach绑定仅在第一次工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
NotFoundError: Node was not found.
NotFoundError: Node was not found.
推荐答案
<button type=button data-bind="click: updateEvents">Update</button>
<ul data-bind="foreach: data.Events">
<li><span data-bind="text: Name"></span></li>
</ul>
var viewModel = {
data: ko.mapping.fromJS({"Events":[]}),
updateEvents: function() {
var self = this;
$.getJSON("/events/", function (data) {
ko.mapping.fromJS(newData, self.data);
});
}
};
ko.applyBindings(viewModel);