繁体   English   中英

如何取消订阅淘汰赛中订阅的功能?

[英]How to unsubscribe the subscribed function in knockout?

我已经订阅了使用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,怎么做?

将调用的结果存储在变量中(或者,在您的情况下,在数组中)。

如果您想取消订阅,只需在每个订阅上调用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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM