如何在淘汰赛中取消订阅订阅的function?
我已经订阅函数来使用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,怎么做?
将订阅的结果存储在一个variables中(或者在你的情况下,存储在一个数组中)。
当你想取消订阅,只需在每个订阅调用处置。
在这里完整描述 – 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 }