knockout.jsko-custom-binding

Dispose event for knockoutjs custom binding


I am trying to develop a widget using knockoutjs custom binding.

The widget would subscribe to an observable for the logged in user, so that its UI would change when a user logs in/out. I figured out that the subscribing has to be done in the init function, but am unable to figure out where to dispose the subscription once the widget is destroyed, i.e. removed from the DOM.

The documentation mentions init and update - but how do I "dispose" a custom binding?


Solution

  • In your init function do something like

    ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
        //act on element disposal
    });