ko.observableArray support for associative arrays

前端 未结 2 1630
感动是毒
感动是毒 2021-02-19 10:56

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

viewModel = {
    a: ko.observableArray(),
    a_assoc: {},
    add_item: functi         


        
2条回答
  •  无人共我
    2021-02-19 11:27

    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);
    

    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.

    Sample here: http://jsfiddle.net/rniemeyer/PgceN/

提交回复
热议问题