我正在使用 Kendo UI 的 MVVM 框架来处理某些事情,但它设置可观察值和可观察数组的方式遇到了令人沮丧且不良的行为。
本质上,如果您使用 set
函数将 Observable 或 ObservableArray 设置为新内容,则该对象上现有的绑定(bind)事件将会丢失。我这里有一些代码要展示,还有一个 jsBin 要演示。
jsBIN
Demonstration
HTML
<div id="binding-content">
<button data-bind="click: onUpdate">Update</button>
</div>
MVVM
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);
最佳答案
change
事件冒泡 - 与其绑定(bind) Mutations
的更改事件,为什么不绑定(bind)到顶级 View 模型,然后检查该事件查看哪个字段触发了更改:
viewModel.bind("change", function (e) {
console.log(e);
console.log(e.field + ' changed');
});
编辑:
如果您确实认为需要绑定(bind)到内部 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"
});
这将保留您的更改
绑定(bind)(但可能会更慢)。
关于kendo-ui - kendo mvvm - "set"将覆盖绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20152901/