Using attr binding in a knockout with the boolean attribute "autofocus"

For some attributes, this is the presence of an attribute that has an effect - the value assigned to it does not matter. For example, the autofocus attribute can be set to false or true, or banana, and the item is still automatically focused. IE, all are equivalent and cause the div to get focus:

<div autofocus="false" contenteditable="true"></div> <div autofocus="true" contenteditable="true"></div> <div autofocus="banana" contenteditable="true"></div> 

The knockout has an attr binding, but it seems to be useful only for assigning values ​​to attributes, and not for adding / removing attributes.

Is there any other way to do this in a knockout, or am I forced to install it from javascript?

NB Using chrome on ubuntu.

+7
source share
4 answers

Use the boolean false to remove the attribute, use the string "false" to set the attribute. What else do you want?

eg:

 // Set as boolean, removes the attribute autofocus(false); // Set as boolean, adds the attribute autofocus(true); // Set as string, adds the attribute autofocus('false'); // Set as string, adds the attribute autofocus('true'); 

See an example here: http://jsfiddle.net/badsyntax/XMDFh/

+6
source

You can use hasfocus binding for knockout:

 <input data-bind="hasfocus: isSelected" /> 

More details here: http://knockoutjs.com/documentation/hasfocus-binding.html

+1
source

You can write a kohandler that removes attributes using jquery.

0
source

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/

0
source

All Articles