Hey I would love to know what you think while reading my posts. Please comment!.

Knockoutjs conditional attribute binding

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); 
                } 
            } 
        } 
    } 
};

About Me

Tim James I'm Tim, a web applications developer from Glasgow, Scotland. Currently working for Kingfisher Systems Ltd, building bespoke systems within the Car Auction industry.

  • C#
  • VB.NET
  • ASP.NET
  • .NET MVC
  • Web API
  • Razor
  • HTML5
  • CSS3
  • jQuery
  • WCF
  • SQL
  • knockout.js
  • Angularjs
  • AJAX
  • APIs
  • SignalR
Why not follow me on twitter? Follow me on Twitter