Knockoutjs: multiple for="..." ids on a single record
This is an enhancement to the code in http://stackoverflow.com/questions/9233176/unique-ids-in-knockout-js-templates
It's still not the prettiest thing.
ko.bindingHandlers.uniqueId = { /* data-bind="uniqueId: $data" to stick a new id on $data and use it as the html id of the element. data-which="foo" (optional) adds foo to the id, to separate it from other ids made from this same $data. */ counter: 0, _ensureId: function (value, element) { if (value.id === undefined) { value.id = "elem" + (++ko.bindingHandlers.uniqueId.counter); } var id = value.id, which = element.getAttribute("data-which"); if (which) { id += "-" + which; } return id; }, init: function(element, valueAccessor) { var value = valueAccessor(); element.id = ko.bindingHandlers.uniqueId._ensureId(value, element); }, }; ko.bindingHandlers.uniqueFor = { /* data-bind="uniqueFor: $data" works like uniqueId above, and adds a for="the-new-id" attr to this element. data-which="foo" (optional) works like it does with uniqueId. */ init: function(element, valueAccessor) { element.setAttribute( "for", ko.bindingHandlers.uniqueId._ensureId(valueAccessor(), element)); } };
Now you can have multiple labeled checkboxes for one record with automatic ids:
<li data-bind="foreach: channel"><input type="checkbox" data-which="mute" data-bind="uniqueId: $data, checked: mute"><label data-which="mute" data-bind="uniqueFor: $data">Mute</label><input type="checkbox" data-which="solo" data-bind="uniqueId: $data, checked: solo">
<label data-which="solo" data-bind="uniqueFor: $data">Solo</label>
</li>
comments failed- HTTPConnectionPool(host='bang', port=9031): Max retries exceeded with url: /public/comments (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f29e3ff9c88>: Failed to establish a new connection: [Errno 111] Connection refused',))
(prev/next buttons not implemented; use search)