aaa
aaa

Reputation: 1124

Knockout - how to update an computed observableArray before using its value in some function

I have one computed observableArray that is bound directly to some radio button and one event bound to that radio button selection. The radio button selection adds some value to array also the selection triggers event where I use the array value.

The problem I am facing is that the array is getting updated(via computed logic) after event function is executed but I have to check the array content(primarily length) in the event function itself. If I use the function as it is now, I am getting the older value. Is there a way that I can force the array to update the values ( evaluate computed value) before I can use it in the event function?

<input type="radio" data-bind="attr: {name: name}, checked: val, event :{ change: $parent.Changed }" value="No" />

//    Knockout code
this.Items = ko.computed(function () {
    //Add selected items to ItemsArray
}
this.Changed = function () {
    if (self.Items().length > 2) {
        //Do sth
    }
}

Upvotes: 0

Views: 426

Answers (1)

Shalom Aleichem
Shalom Aleichem

Reputation: 3027

Instead of having a computed observable and change event binding you can subscribe to the observable that is bound to the checked property. In the subscribed function you can calculate Items array at first and then do your length check:

this.val.subscribe(function (newVal) {
    // update Items array
    ...

    //
    if (self.Items().length > 2) {
        ...
    }
});

Upvotes: 1

Related Questions