Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ko.observableArray support for associative arrays

Tags:

knockout.js

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');
like image 886
Randall Stevens Avatar asked Jun 22 '11 18:06

Randall Stevens


1 Answers

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/

like image 77
RP Niemeyer Avatar answered Oct 26 '22 11:10

RP Niemeyer