Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout: click & checked bindings in one element

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>
like image 871
Ozerich Avatar asked Nov 25 '12 20:11

Ozerich


People also ask

What is data bind click?

Click binding is one of the simplest binding and is used to invoke a JavaScript function associated with a DOM element based on a click. This binding works like an event handler. This is most commonly used with elements such as button, input, and a, but actually works with any visible DOM element.

What is Ko applyBindings?

The ko. applyBindings method activates Knockout and wires up the view-model to the view. Now that we have a view-model, we can create the bindings. In Knockout.js, you do this by adding data-bind attributes to HTML elements.

What is Knockout code?

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model.

How do you activate Knockout?

To activate Knockout, add the following line to a <script> block: ko. applyBindings(myViewModel); You can either put the script block at the bottom of your HTML document, or you can put it at the top and wrap the contents in a DOM-ready handler such as jQuery's $ function.


2 Answers

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/

like image 86
Tariqulazam Avatar answered Oct 07 '22 14:10

Tariqulazam


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

like image 20
Lerin Sonberg Avatar answered Oct 07 '22 13:10

Lerin Sonberg