我已经订阅了使用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,怎么做?
答案 0 :(得分:95)
将订阅的调用结果存储在变量中(或者,在您的情况下,存储在数组中)。
如果您想取消订阅,只需在每个订阅上调用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
}