user471317
user471317

Reputation: 1231

Knockout observable - why is this value being updated automatically?

I have an array of names that I use to populate a FilterBy radio button list.

filterBy = ko.observableArray(["Aaa", "Bbb", "Ccc"]);
selectedFilter = ko.observable("Aaa");

I display the FilterBy radio button list like this,

<div data-bind="foreach: filterBy">
    <input type="radio" name="filterby" data-bind="value: $data, checked: $parent.selectedFilterBy" /><span data-bind="text: $data"></span>
</div>

I have two buttons - Submit and Cancel. On submit click, I get the selected radio button and assign its value to 'selectedFilterBy' and do the filtering/updating etc. On cancel click, I want restore the selectedfilter. I just noticed that the value of selectedFilterBy is being updated as I select each radio button. I was not expecting 'selectedFilterBy' to update automatically.

Any idea why?

Thanks.

Upvotes: 0

Views: 134

Answers (1)

Ashwin
Ashwin

Reputation: 262

The checked binding has been set to update the model $parent.selectedFilterBy. So whenever the radio button is clicked the checked binding is invoked and since Knockout is 2 way binding, it will update the specified variable.

When the user changes which radio button is selected, KO will set your model property to equal the value of the selected radio button"

Upvotes: 1

Related Questions