[英]Unsubscribe in Observable KnockOutJS
Im currently using KnockOut JS and i conducted some research about when the observable is notified it will fire a function which is like this 我目前正在使用KnockOut JS,我进行了一些关于何时通知observable的研究它会激活一个像这样的函数
function FunctionToSubscribe()
{
}
var TestObservable = ko.observableArray([]);
TestObservable.subscribe(FunctionToSubscribe);
i am subscribing FunctionToSubscribe
in this event 我在这个活动中订阅了
FunctionToSubscribe
im currently thinking is there a way to unsubscribe it? 我目前在想是否有办法取消订阅? like we do in c#?
就像我们在c#中做的那样? when unsubscribing events anyone have an idea regarding this???
当取消订阅事件时,任何人都对此有所了解???
The subscribe
function returns the "subscription" object which has a dispose
method what you can use to unsubscribe: subscribe
函数返回“subscription”对象,该对象具有可用于取消订阅的dispose
方法:
var TestObservable = ko.observableArray([]);
var subscription = TestObservable.subscribe(FunctionToSubscribe);
//call dispose when you want to unsubscribe
subscription.dispose();
See also in the documentation: Explicitly subscribing to observables 另见文档: 明确订阅observables
You can use dispose
method. 您可以使用
dispose
方法。
function FunctionToSubscribe()
{
}
var TestObservable = ko.observableArray([]);
// subscribe
var subscriber = TestObservable.subscribe(FunctionToSubscribe);
// unsubscribe
subscriber.dispose();
In my case I needed to temporarily pause the subscription and do some work so I ended up doing this: 在我的情况下,我需要暂时暂停订阅并做一些工作,所以我最终这样做:
ko.subscribable.fn.suspendableSubscribe = function (callback, callbackTarget, event) {
var isSuspended = false;
return ko.utils.extend(this.subscribe(function () {
if (!isSuspended)
return callback.apply(this, arguments);
}, callbackTarget, event), {
suspend: function () { isSuspended = true; },
resume: function () { isSuspended = false; }
});
};
Usage 用法
var name = ko.observable('CodingYoshi');
var subscription = name.suspendableSubscribe(function(){ // code... });
subscription.suspend();
name('CodingYoshi2');
subscription.resume();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.