$(document).ready(function () {
var Item = function (isSelected, isEnabled, errorState,
name, group, processed, errors, state) {
var self = this;
self._isSelected = ko.observable(isSelected);
self._isEnabled = ko.observable(isEnabled);
self._errorState = ko.observable(errorState);
self._name = ko.observable(name);
self._group = ko.observable(group);
self._processed = ko.observable(processed);
self._errors = ko.observable(errors);
self._state = ko.observable(state);
};
function ViewModel() {
var self = this;
self.SentinelList= ko.observableArray([
ko.observable(new Item(false, false, false, 'Mail1', 'Mailing', 4, 0, 1)),
ko.observable(new Item(false, false, false, 'Ident1', 'Identity', 5, 0, 0)),
ko.observable(new Item(false, false, false, 'Cook', 'Look', 2, 0, 1))]);
}
var vm = new ViewModel();
for (var item in vm.SentinelList) {
item.subscribe(function () {
console.log('List changed');
});
}
ko.applyBindings(vm);
});
答案 0 :(得分:7)
您可以对数组使用subscribe:
self.SentinelList.subscribe(function (changes) {
changes.forEach(function (change) {
if (change.status === 'added') {
console.log('new item !!');
change.value.subcriptions.push(change.value.subscribe(event));
} else if (change.status === 'deleted') {
ko.utils.arrayForEach(change.value.subcriptions, function(s) {
if(s) s.dispose();
}
);
console.log('deleted item !!');
}
});
}, null, "arrayChange");
<强> See fiddle 强>
答案 1 :(得分:2)
您可以使用跟踪视图模型更改的外部插件。例如KO-Reactor
https://github.com/ZiadJ/knockoutjs-reactor
在这种情况下,订阅看起来像
for(var i = 0; i < vm.SentinelList().length; i++){
ko.watch(vm.SentinelList()[i], { recurse: true }, function(params, modifiedProperty) {
console.log('SentinelList changed');
});
}
<强> JSFIDDLE 强>