Conditionally add an element attribute in knockout.js

I needed this when selecting an <option> (that I was generating manually instead of built-in knockout).

<option 
 data-bind="text: text, 
    attr:{
     value:value,
     'selected': typeof(selected) !== 'undefined' ? selected : null 
     }">
 Choice X
</option>

This says to always update the 'text' attribute and to add the 'value' attribute, but only add 'selected' if the the data already has a value of 'selected' defined.


You can create a custom binding attrIf which will check the value of a specific observable boolean before add or not the attributes. See this example:

ko.bindingHandlers.attrIf = {
    update: function (element, valueAccessor, allBindingsAccessor) {
        var h = ko.utils.unwrapObservable(valueAccessor());
        var show = ko.utils.unwrapObservable(h._if);
        if (show) {
            ko.bindingHandlers.attr.update(element, valueAccessor, allBindingsAccessor);
        } else {
            for (var k in h) {
                if (h.hasOwnProperty(k) && k.indexOf("_") !== 0) {
                    $(element).removeAttr(k);
                }
            }
        }
    }
};

<a href="#" data-bind="attrIf: {title: title, _if: flag}">link</a>

Knockout's "attr" data binding does support this scenario just return null or undefined from your getDisabledState() function then it won't emit the attribute.

This answer was retrieved from Knockout attr binding with attributes like 'readonly' and 'disabled'


I wish I could have just replied to @gbs, but I can't. My solution would have been to have two of the same HTML element, one with the attribute, one without, and a knockout condition to add one of it according to the element. I also know about this custom biding, but which of the solution is more efficient?