Javascript 如何在淘汰赛中取消订阅已订阅的功能?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10653030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to unsubscribe the subscribed function in knockout?
提问by BalaKrishnan?
I already subscribe the function to listen the property value change using ko.
我已经订阅了使用 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;
);
}
here i want to unsubscribe the notifyChange from myViewModel's property one by one, how to do this?
这里我想从myViewModel的属性中一一取消订阅notifyChange,怎么做?
回答by Artem
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.
当您想取消订阅时,只需对每个订阅调用 dispose 即可。
Fully described here - http://knockoutjs.com/documentation/observables.html
这里有完整的描述 - 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
}