使用knockoutjs我有一个可观察的数组,子元素也是可观察的。可观察数组通过foreach绑定。当我更新数组的元素时,视图不会更新。
为什么?
我这里有一个jsfiddle - > http://jsfiddle.net/axUm6/7/
<ul data-bind="foreach: someList">
<li>
<div style="float: left" data-bind="text: name"></div>
<div style="padding-left: 50px;" class="update">update</div>
</li>
</ul>
vmTemplate = function () {
var self = this;
self.someList = ko.observableArray();
self.init = function () {
self.someList.push(ko.observable({name: 'test 1'}));
self.someList.push(ko.observable({name: 'test 2'}));
$(document).on('click', '.update', function () {
var itemToUpdate = ko.dataFor(this);
self.alertTheList();
itemToUpdate.name = 'test 3';
self.alertTheList();
self.someList.valueHasMutated();
}); //on click
}; //init
self.alertTheList=function(){
var message='';
for(var i=0;i<self.someList().length;i++){
message+=self.someList()[i]().name;
}
alert(message);
};//alertTheList
};
var vm = new vmTemplate();
vm.init();
ko.applyBindings(vm);
答案 0 :(得分:2)
您应该使用具有可观察属性的ItemViewModel而不是self.someList.push(ko.observable(...))。看example。另外,我在敲除绑定时更改了jQuery click事件处理程序。
HTML:
<ul data-bind="foreach: someList">
<li>
<div style="float: left" data-bind="text: name"></div>
<div style="padding-left: 50px;" class="update" data-bind="click: $parent.updateName">update</div>
</li>
</ul>
视图模型:
ItemViewModel = function(val) {
var self = this;
self.name = ko.observable(val);
}
vmTemplate = function () {
var self = this;
self.someList = ko.observableArray();
self.init = function () {
self.someList.push(new ItemViewModel('test 1'));
self.someList.push(new ItemViewModel('test 2'));
}; //init
self.updateName = function(item) {
self.alertTheList();
item.name('test 3');
self.alertTheList();
}; //on click
self.alertTheList=function(){
var message='';
for(var i=0;i<self.someList().length;i++){
message+=self.someList()[i].name();
}
alert(message);
};//alertTheList
};
var vm = new vmTemplate();
vm.init();
ko.applyBindings(vm);