Mapping: foreach binding work only the first time

痴心易碎 提交于 2019-12-04 19:32:12

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

My friend Thomas Brattli found the solution:

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

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

Thanks !

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!