Search code examples
functionknockout.jsradio-button

Knockoutjs - checked radio doesn't call function


Is there any way to bind checked radio with function which add new object to my array?

JS

ViewModel = function(path) {
    var self = this;

    self.regions = ko.observableArray();

    self.addRegion = function() {
        self.regions.push(new Ticketon.Performance.Region());
    };
}

Region = function() {
    var self = this;

    self.name = ko.observable();
    self.description = ko.observable();
};

HTML

<label><input type="radio"  name="regionCount" checked="checked"> One region</label>
<label><input type="radio" name="regionCount" data-bind="checked: addRegion"> Two regions</label>

This do nothing... When I change CHECKED on CLICK it works, but when I click more times on the radio, there is more regions in array.


Solution

  • The checked binding stores the value (that you would specify using the value attribute) to an observable. It's not expecting a function.

    To do what you're intending, you would need to use the click binding. If you want to limit or toggle the number of regions, the function would need to perform this logic.