1

我在 HTML 文件中有以下JQuery片段:

$.getJSON("/events/", function (data) {
    viewModel = ko.mapping.fromJS(data);
    ko.applyBindings(viewModel);
});

例如,当用户按下按钮并返回 JSON 时,将执行代码,如下所示:

{"Events":[{"Name":"Event1"},{"Name":"Event2"},{"Name":"Event3"}]}

此结果链接(使用KnockoutJS)到:

<ul data-bind="foreach: Events">
    <li><span data-bind="text: Name"></span></li>
</ul>

第一次调用. $.GetJSON我得到了我想要的,即(浏览器输出):

  • 事件1
  • 事件2
  • 事件3

但在随后对“$.GetJSON”的调用中,我在Firebug中收到以下错误:

NotFoundError: Node was not found.

containerNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);

而且我没有得到任何列表项。

我可能做错了什么?

非常感谢您提前。

4

2 回答 2

1

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:

<button type=button data-bind="click: updateEvents">Update</button>
<ul data-bind="foreach: data.Events">
    <li><span data-bind="text: Name"></span></li>
</ul>

Javascript:

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);​
于 2012-09-20T02:21:43.553 回答
1

我的朋友 Thomas Brattli 找到了解决方案:

<ul data-bind="template: { name: 'template', foreach: Events }"></ul>

<script id="template" type="text/html">
    <li><span data-bind="text: Name"></span></li>
</script>

谢谢 !

于 2012-09-10T21:28:22.520 回答