KnockoutJS Unapply Bindings

So, you’re getting pretty advanced with your [Knockout](http://knockoutjs.com/) magic, but struggle with the fact that you’re restricted to binding once to your page or DOM element. (See this [question ](http://stackoverflow.com/questions/10048485/how-to-clear-remove-observable-bindings-in-knockout-js) on stackoverflow as an example.) KnockoutJS doesn’t come default with an `unapplyBindings()` method. After some testing for memory leaks and using it in a fairly large project, I’ve come up with a solution that works. It’s fairly self explanatory.

:javascript:
// accepts jQuery node and remove boolean
ko.unapplyBindings = function ($node, remove) {
// unbind events
$node.find(“*”).each(function () {
$(this).unbind();
});

// Remove KO subscriptions and references
if (remove) {
ko.removeNode($node[0]);
} else {
ko.cleanNode($node[0]);
}
};

With this new `ko.unapplyBindings` method, you can now write KnockoutJS modules that can be dynamically initialized and removed. Tune in later for an advanced article about how I make use of this new-found power to enable some pretty complex interfaces.

6 thoughts on “KnockoutJS Unapply Bindings”

  1. I am very new to Knockout and am mostly piecing together things I have found to create a facebook style comment system using Knockout and SignalR. I have had difficulty figuring out how to keep particular nodes in my DOM from being bound by Knockout. This post seems to come closest to what may be my solution, but I am unsure how to implement it. How do I actually call this function on a node? Do I set the data-bind property to this function? (fyi…My elements are being created in a foreach loop so I can only identify them by class name).

Leave a Reply