通知该值在纯数组中更改 [英] Notify that value changed in plain array

查看:52
本文介绍了通知该值在纯数组中更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我将绑定到普通数组.数组的值可以由外部组件更改.

Currently I'm bound to plain array. Values of the array can be changed by external components.

是否有可能发送值已更改的通知并重新呈现DOM树?

Is there any possibility to send notification that value has changed and re-render DOM tree?

我无法使用可观察对象,因此valueHasMutated不是解决方案,数组非常大,并且其中包含许多复杂的对象.

I can't use observables, thus valueHasMutated is not a solution, array is very large and contains lot of complex objects in it.

推荐答案

如果我理解正确,则该数组是ViewModel的成员(您可以控制该数组),但是您不能将其更改为observableArray,这是因为在控件外部,使用纯数组语法修改数组.另外,在这些黑盒功能运行之后,您可以采取一些措施,以通知模型该阵列可能已经变异.

If I understand correctly, the array is a member of the ViewModel (which you have control over), but you cannot change it into an observableArray because things outside of your control modify the array, using plain array syntax. Also, you can take some action after these black-box functions run, to notify the model that the array may have been mutated.

我们可以做到这一点.定义一个(内部)observableArray并在包装它的ViewModel上定义一个公共属性.这使您可以使用普通数组语法访问observableArray.但是,对数组中各个元素(非observable)的更改不会发送通知,因此您需要提供对内部valueHasMutated方法的调用,每次进行更改时都将调用该调用.

We can do this. Define an (internal) observableArray and define a public property on the ViewModel that wraps it. That gives you access to the observableArray using ordinary array syntax. However, changes to individual (non-observable) elements of an array do not send notifications, so you will need to provide a call to the valueHasMutated method of the internal observableArray, to be called whenever you make changes.

var vm = (function () {
    var arrayImpl = ['hi'];
    var obsArray = ko.observableArray(arrayImpl);
    var itemNumbers = [1,2,3,4,5,6,7,8,9];

    var self = {
        itemNumbers: itemNumbers,
        selectedItemNumber: ko.observable(1),
        newValue: ko.observable(),
        arrayHasMutated:obsArray.valueHasMutated
    };
    Object.defineProperty(self, 'plainArray', {
        get: obsArray,
        set: obsArray
    });
    return self;
});

ko.applyBindings(vm);

我们的应用程序可以像常规数组一样使用plainArray属性.更新完成后,呼叫arrayHasMutated.

Our app can use the plainArray property just like a regular array. When updates are made, call arrayHasMutated.

Item Number: <select data-bind="options:itemNumbers, value:selectedItemNumber"></select>
<br />
New Value: <input data-bind="value:newValue" />
<button data-bind="click:function () { var idx=selectedItemNumber()-1; plainArray[idx] = newValue(); arrayHasMutated(); }">Set it</button>
<ol data-bind="foreach:plainArray">
    <li data-bind="text:$data"></li>
</ol>
<br />
Length: <span data-bind="text:plainArray.length"></span>

尝试一下: http://jsfiddle.net/4jogh3k5/1/

这篇关于通知该值在纯数组中更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆