0

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.