Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating IDs within Knockout Foreach loops

I'm trying to build some HTML with Knockout that Jquery UI can turn into toggle buttons. What I need to arrive at is this:

<div id="status">
    <input type="radio" id="status_ACTIVE" value="ACTIVE" name="status" /><label for="status_ACTIVE">Active</label>
    <input type="radio" id="status_INACTIVE" value="INACTIVE" name="status" checked="checked" /><label for="status_INACTIVE">Inactive</label>
</div>

Using JQuery UI I can easily turn that into toggle buttons. But how do I generate that without using the now depreciated JQuery Templates? This is what I attempted to do:

Inside the javascript model:

self.statuses = [{Selected:true,Text:"Active",Value:"ACTIVE"},{Selected:false,Text:"Inactive",Value:"INACTIVE"}];

The markup:

<div id="status" data-bind="foreach: statuses">
    <input type="radio" name="status" data-bind="value: Value, id: 'status_' + Value" /><label data-bind="text: Text, for: 'status_' + Value"></label>
</div>

This doesn't work. I don't think it likes how I'm trying to create that ID, or associate it with the for in the loop. It draws the buttons incorrectly, as two independent buttons and the click functionality doesn't work.

Even if I just specify the value as the id like: id: Value and for: Value it still doesn't work. Can I not set these attributes using knockout?

like image 509
Arbiter Avatar asked Jan 25 '12 19:01

Arbiter


People also ask

For what purpose do we use foreach binding in Ko?

Purpose. The foreach binding duplicates a section of markup for each entry in an array, and binds each copy of that markup to the corresponding array item. This is especially useful for rendering lists or tables.

What is $data in knockout?

The $data variable is a built-in variable used to refer to the current object being bound. In the example this is the one of the elements in the viewModel.

What is the abbreviation used for KnockoutJS?

KO is an abbreviation used for KnockoutJS. KO supports all mainstream browsers - IE 6+, Firefox 3.5+, Chrome, Opera, Safari (desktop/mobile).


1 Answers

Adding this javascript solved my issue:

ko.bindingHandlers.id = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
    },
    update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        $(element).attr('id', valueAccessor());
    }
};

ko.bindingHandlers.forattr = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
    },
    update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        $(element).attr('for', valueAccessor());
    }
};

I did have to change for: 'status_' + Value into foratt: 'status_' + Value as for is a reserved word.

Update: I could have also used the "attr" binding, like this:

attr: { for: 'status_' + Value }
like image 58
Arbiter Avatar answered Sep 28 '22 09:09

Arbiter