如何在淘汰赛中取消订阅已订阅的功能? [英] How to unsubscribe the subscribed function in knockout?

查看:102
本文介绍了如何在淘汰赛中取消订阅已订阅的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经预订了使用ko监听属性值更改的功能.

I already subscribe the function to listen the property value change using 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,该怎么做?

here i want to unsubscribe the notifyChange from myViewModel's property one by one, how to do this?

推荐答案

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

Store results of call to subscriptions in a variable (or, in your case, in an array).

要取消订阅,只需对每个订阅调用dispose.

When you want to unsubscribe, simply call dispose on each subscription.

此处有完整说明- 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
}

这篇关于如何在淘汰赛中取消订阅已订阅的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆