如何退订淘汰赛订阅功能?(How to unsubscribe the subscribed fun

2019-07-29 10:35发布

我已经订阅功能收听使用KO属性值的变化。

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

var postbox = new ko.subscribable();
var myViewModel =
{
    FirstName: ko.observable( "Bert" ),
    LastName: ko.observable( "pual" )
};
var sub = null;
for ( var i in myViewModel ) {
    var model = myViewModel[i];
    model.subscribe( self.notifyChange.bind( model, i ) );

}

$( '#unsubscribeButton' ).click( function () {
    // here i want to unsubscribe.
} );
 ko.applyBindings( myViewModel );
  });
 notifyChange = function ( PropName, newValue ) {
var self= this;
);
    }

在这里,我想通过一个退订从myViewModel的财产之一,有NotifyChange,如何做到这一点?

Answer 1:

在一个变量调用订阅结果存储(或者,在你的情况下,在一个阵列)。

如果要取消订阅,只需调用Dispose每个订阅。

完全形容这里- http://knockoutjs.com/documentation/observables.html

您的代码看起来就像这样:

//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
}


文章来源: How to unsubscribe the subscribed function in knockout?