How to clear/remove observable bindings in Knockout.js?

后端 未结 9 1961
忘了有多久
忘了有多久 2020-11-29 16:40

I\'m building functionality onto a webpage which the user can perform multiple times. Through the user\'s action, an object/model is created and applied to HTML using ko.app

9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-29 17:23

    For a project I'm working on, I wrote a simple ko.unapplyBindings function that accepts a jQuery node and the remove boolean. It first unbinds all jQuery events as ko.cleanNode method doesn't take care of that. I've tested for memory leaks, and it appears to work just fine.

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

提交回复
热议问题