CyclingFreak
CyclingFreak

Reputation: 1625

KnockoutJs: directly address observableArray object in view

I want to loop through an observableArray of objects and in this loop, I have to get the corresponding value of another observableArray. I do not succeed in doing this.

My code is as follow.

Model and viewmodel:

//**********MODEL********************
function Configuration() {
var self = this;

self.properties = ko.observableArray();
}

function deviceProperty() {
    var self = this;

    self.property = ko.observable("");
    self.value = ko.observable("");
}

//**********VIEWMODEL****************
function compareModelView() {
var self = this;

self.config1 = ko.observable(new Configuration);
self.config2 = ko.observable(new Configuration);

$().ready(function () {
    //Load config1 and config2
});

}

//**********jQuery********************
(function ($) {
    $(document).ready(function () {
        ko.applyBindings(new compareModelView());
    });
})(jQuery);

View:

<!-- ko foreach: config1().properties -->
     <tr>
     <td data-bind="text: property()"></td>
     <td data-bind="text: value()"></td>
     <td data-bind="text: $root.config2().properties()[$index].value()"></td>
     </tr>
<!-- /ko -->

Knockoutjs gives an error, saying that this property doesn't exist.

When I do $root.config2().properties().length it returns a number (3). When I do $root.config2().properties()[0] it returns [Object][Object]. When I do $root.config2().properties()[0] it returns an empty string.

But I can't see how I can directly address the value property inside the object?

Upvotes: 1

Views: 585

Answers (1)

nemesv
nemesv

Reputation: 139758

$index is an observable property (see doc), so you need to write $index() to get its value.

So the following binding should work:

<td data-bind="text: $root.config2().properties()[$index()].value()"></td>

Although your main problem was the $index() but in itself it won't solve your case because the population order of the collections does matter in this scenario so you get errors with your current setup.

So if you populate first the config1() KO starts to bind your table but if the config2() has not been populated yet you will get the some undefined errors. To fix it you need change the population order to populate the config2() first.

You can play with this here: http://jsfiddle.net/xwjKK just change the order pupulateConfig2 and pupulateConfig1 call to see the effect.

Upvotes: 1

Related Questions