48

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

4

1 回答 1

100

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

当您想取消订阅时,只需在每个订阅上调用 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
}
于 2012-05-18T13:37:28.513 回答