Knockout: click & checked bindings in one element
Asked Answered
R

2

15

I have array of limits, and checkboxes for enable/disable limits. But checkboxes do not work

jsFiddle

function Limit(start, end)
{
    var that = this;

    this.start = start;
    this.end = end;

    this.label = ko.computed(function(){
        return that.start + ' - ' + that.end;            
    });
}

function ViewModel()
{
    var that = this;

    this.limits = [new Limit(1,2), new Limit(3,4), new Limit(4,5)];

    this.activeLimit = ko.observable(that.limits[0]);

    this.changeActiveLimit = function(limit)
    {
            that.activeLimit(limit);
    }
}

ko.applyBindings(new ViewModel());​

My HTML

<div data-bind="foreach: {data: limits, as: 'limit'}">
 <input type="checkbox" data-bind="click: $root.changeActiveLimit, checked: limit.label == $root.activeLimit().label"/>
    <span data-bind="text: limit.label"/> 

</div>
Rectocele answered 25/11, 2012 at 20:41 Comment(0)
S
15

If you Modify your viewModel like below it will work

function ViewModel()
{
    var that = this;

    this.limits = [new Limit(1,2), new Limit(3,4), new Limit(4,5)];

    this.activeLimit = ko.observable(that.limits[0]);

    this.changeActiveLimit = function(limit)
    {
            that.activeLimit(limit);
            return true;
    }
}

return true is the critical part here.

Here is a working fiddle http://jsfiddle.net/tariqulazam/WtPM9/10/

Syman answered 25/11, 2012 at 21:0 Comment(1)
return true; helps me. Thanks a lot!Rectocele
C
13

The key is to return true; at the end of the click handler function! This updates the UI correctly.

Catbird answered 13/10, 2013 at 10:13 Comment(1)
Thanks you !! This is the answer I was looking for !Accouplement

© 2022 - 2024 — McMap. All rights reserved.