Generation of identifiers in Foreach knockout cycles

I am trying to create knockout HTML that jQuery UI can turn into toggle buttons. What I need is:

<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 this into toggle buttons. But how can I generate this without using the now impaired jQuery templates? This is what I tried to do:

Inside the javascript model:

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

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 does not work. I don’t think I like the way I try to create this identifier, or associate it with for in a loop. He draws the buttons incorrectly, as the two independent buttons and the click function do not work.

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

+7
source share
1 answer

Adding this javascript solved my problem:

 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 had to change for: 'status_' + Value to foratt: 'status_' + Value , since for is a reserved word.

Update: I could also use the attr binding, for example:

 attr: { for: 'status_' + Value } 
+10
source

All Articles