kendo-ui - kendo mvvm - "set"将覆盖绑定(bind)

标签 kendo-ui

我正在使用 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/

相关文章:

javascript - Kendo UI - 将参数传递给 read().data() 中的 JS 函数

telerik - Kendo DatePicker 无法验证自定义日期格式

javascript - Kendo 日期选择器 - 将错误的日期格式传递给 Controller

javascript - 热衷于使用 JavaScript 或 Jquery 从剑道下拉列表中获取值/文本对

kendo-ui - 为我的 json 数据配置 kendo ui treeview

javascript - 根据条件禁用剑道网格中的行

javascript - 在特定 View 中禁用抽屉的滑动打开

kendo-ui - Kendo Grid - 验证消息未显示在网格中的自定义编辑器上

javascript - 单元测试使用 Kendo Grid/Datasource 的 Angular Controller

javascript - 在剑道自动完成中获取选定的对象