How to unsubscribe the subscribed function in knockout?

前端 未结 1 1530
误落风尘
误落风尘 2021-02-02 06:00

I already subscribe the function to listen the property value change using ko.

var self = this;
$( document ).ready( function () {

var postbox = new ko.subscrib         


        
1条回答
  •  日久生厌
    2021-02-02 06:49

    Store results of call to subscriptions in a variable (or, in your case, in an array).

    When you want to unsubscribe, simply call dispose on each subscription.

    Fully described here - http://knockoutjs.com/documentation/observables.html

    Your code will look like this:

    //store subscriptions in array
    var subscriptions = [];
    
    for ( var i in myViewModel ) {
        var model = myViewModel[i];
        subscriptions.push(model.subscribe( self.notifyChange.bind( model, i ) ));
    }
    
    
    //unsubscribe
    for(var i in subscriptions) {
        subscriptions[i].dispose(); //no longer want notifications
    }
    

    0 讨论(0)
提交回复
热议问题