我正在使用Kendo UI的MVVM框架进行某些操作,并且遇到了令人沮丧和不受欢迎的行为,它设置了observable和可观察数组.
实质上,如果使用该set函数将Observable或ObservableArray设置为新的,则该对象上的现有绑定事件将丢失.我在这里展示了一些代码,并展示了一个jsBin.
<div id="binding-content">
<button data-bind="click: onUpdate">Update</button>
</div>
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)
该change事件冒泡-而不是绑定change事件Mutations,你为什么不绑定到顶级视图模型,然后检查活动,看看哪些领域引发了变化:
viewModel.bind("change", function (e) {
console.log(e);
console.log(e.field + ' changed');
});
Run Code Online (Sandbox Code Playgroud)
编辑:
如果你真的认为你需要绑定到内部ObservableArray,那么你可以通过删除所有元素并添加新元素来"替换"数组,所以代替
viewModel.set("Mutations", [{
Id: "items/1",
Value: "test"
}]);
Run Code Online (Sandbox Code Playgroud)
你能做到的
current.splice(0, viewModel.Mutations.length); // remove existing items
current.push({
Id: "items/1",
Value: "test"
});
Run Code Online (Sandbox Code Playgroud)
这将保留你的change绑定(但它可能会更慢).
| 归档时间: |
|
| 查看次数: |
4376 次 |
| 最近记录: |