KnockoutJS Unapply Bindings

So, you’re getting pretty advanced with your Knockout magic, but struggle with the fact that you’re restricted to binding once to your page or DOM element. (See this question 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 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.

  • http://twitter.com/LeoJH Leo Hernandez

    Thanks … will be using today

  • Alex

    Thank you

  • Bert Vanhooff

    Nice. Seems to work well and solves my memory leak.