Knockout has no built-in binding to add or remove an attribute, only to set an attribute.
The reason that the hasFocus binding demonstrates the behavior that it performs is because its own .focus() and .blur() methods are used to add or remove focus.
Knockout was previously reported with difficulty managing non-boolean attributes, here is one example where Michael Best mentioned that he would not be considered:
https://github.com/SteveSanderson/knockout/issues/391
Update:
You can create a binding handler on these lines:
ko.bindingHandlers.toggleAttr = { update: function (element, valueAccessor) { var options = ko.utils.unwrapObservable(valueAccessor()); var attr = ko.utils.unwrapObservable(options.attr); var param = ko.utils.unwrapObservable(options.param); param ? element.setAttribute(attr, true) : element.removeAttribute(attr); } };
This will allow you to do this:
<input data-bind="toggleAttr: { attr: 'autofocus', param: focusMe }" />
Here's the script: http://jsfiddle.net/nathanjones/9EzBD/
Nathan jones
source share