我正在使用Kendo UI的MVVM框架进行某些操作,并且遇到了设置observable和可观察数组的方式令人沮丧和不受欢迎的行为。
基本上,如果使用set
函数将Observable或ObservableArray设置为新的,则该对象上的现有绑定事件将丢失。我在这里展示了一些代码,并展示了一个jsBin。
<div id="binding-content">
<button data-bind="click: onUpdate">Update</button>
</div>
var viewModel = new kendo.observable({
Id: "models/1",
Name: "First Model",
Consumable: false,
Equipable: false,
Mutations: [],
Tags: [],
onUpdate: function (e) {
// first, do a simpler change to the mutations
// so that we are not overwriting them
var current = viewModel.get("Mutations");
current.push({
Id: "items/1",
Value: "test"
});
current.push({
Id: "items/2",
Value: "test2"
});
// we will see the 'changed' message twice,
// once for each item pushed into it.
// now, just use the 'set' function
// to completely replace the array
viewModel.set("Mutations", [{
Id: "items/1",
Value: "test"
}]);
// we do not get a third changed event, because
// the set function overwrote the array. We will
// try to add things the old fashioned way again
current = viewModel.get("Mutations");
current.push({
Id: "items/3",
Value: "test3"
});
current.push({
Id: "items/4",
Value: "test4"
});
}
});
viewModel.Mutations.bind("change", function (e) {
console.log('changed');
});
kendo.bind($("#binding-content"), viewModel);
答案 0 :(得分:5)
change
事件冒泡 - 而不是绑定Mutations
的更改事件,为什么不绑定到顶级视图模型然后检查事件以查看哪个字段触发了改变:
viewModel.bind("change", function (e) {
console.log(e);
console.log(e.field + ' changed');
});
编辑:
如果你真的认为你需要绑定到内部的ObservableArray,那么你可以通过删除所有元素并添加新的元素来“替换”数组,所以代替
viewModel.set("Mutations", [{
Id: "items/1",
Value: "test"
}]);
你可以做到
current.splice(0, viewModel.Mutations.length); // remove existing items
current.push({
Id: "items/1",
Value: "test"
});
这会保留你的change
绑定(但可能会更慢)。