Asle G
Asle G

Reputation: 588

How to set knockout variable from array element

I´m having some finger trouble with this:

<p data-bind="text: $root.myArray()[0]"></p>
<hr>
myVal = <span data-bind="text: $root.myVal()></span>    

In viewmodel:

self.myArray = ko.computed(function() {
    var categories = ko.utils.arrayMap(self.selectedItems(), function(item) {
        return item.id();
    });
    return categories.sort();
});             

self.myVal = ko.observable(self.myArray()[0]);

Printing myArray shows the correct value, but myVal is blank. Why?
(and yes, I only want the first value in the array).

Also, I´d like it as a number when I save to database. Do I need to do some kind of typecast then?

Upvotes: 0

Views: 86

Answers (1)

PW Kad
PW Kad

Reputation: 14995

The difference is probably that you are setting the value of myVal to the first object in the array before the array is actually populated. To see this if you console.log(self.myArray()[0]) right before self.myVal is set you should see what is being set. Since you are setting it only once it will not subscribe to change in the array. If you wanted to do this you would use a computed.

self.myVal = ko.computed(function () { return self.myArray()[0]; });

The computed will now fire whenever anything is added to or removed from myArray

Upvotes: 1

Related Questions