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);
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With