ko.observableArray对关联数组的支持 [英] ko.observableArray support for associative arrays

查看:68
本文介绍了ko.observableArray对关联数组的支持的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在更好的(内置的)混合observableArray和关联数组的方法?

Is there a better (built in?) way to mix observableArray and associative arrays?

viewModel = {
    a: ko.observableArray(),
    a_assoc: {},
    add_item: function(i) {
        if (typeof this.a_assoc[i] == 'undefined') {
            this.a.push(i);
            this.a_assoc[i]=1;
        }
    }
}

viewModel.add_item('bla');

推荐答案

通常,您可以在淘汰赛中执行以下操作:

Typically, you would do something like this in Knockout:

var viewModel = {
    a: ko.observableArray(["a","b","c","d"]),
    add_item: function() {
       this.a.push("new" + this.a().length);   
    }
};

viewModel.a_assoc = ko.dependentObservable(function() {
    var result = {};
    ko.utils.arrayForEach(this.a(), function(item) {
       result[item] = 1;
    });
    return result;
}, viewModel);

因此,您有一个dependentObservable,它将数组映射到对象.请注意,每次更新原始数组时,都会重建对象.因此,它的效率不如您的帖子中的方法有效,但是除非您的对象很大,否则是否会导致性能问题值得怀疑.

So, you have a dependentObservable that maps your array to an object. Note that each time that the original array is updated, the object is rebuilt. So, it is less efficient than the method in your post, but unless your object is substantially big, it is doubtful that it would cause a performance issue.

此处提供示例: http://jsfiddle.net/rniemeyer/PgceN/

这篇关于ko.observableArray对关联数组的支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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