最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Unsubscribe in Observable KnockOutJS - Stack Overflow

programmeradmin7浏览0评论

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

function FunctionToSubscribe()
{

}

var TestObservable = ko.observableArray([]);

TestObservable.subscribe(FunctionToSubscribe);

i am subscribing FunctionToSubscribe in this event

im currently thinking is there a way to unsubscribe it? like we do in c#? when unsubscribing events anyone have an idea regarding this???

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

function FunctionToSubscribe()
{

}

var TestObservable = ko.observableArray([]);

TestObservable.subscribe(FunctionToSubscribe);

i am subscribing FunctionToSubscribe in this event

im currently thinking is there a way to unsubscribe it? like we do in c#? when unsubscribing events anyone have an idea regarding this???

Share Improve this question asked Nov 27, 2014 at 6:33 DonDon 1311 silver badge10 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 18

The subscribe function returns the "subscription" object which has a dispose method what you can use to unsubscribe:

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

You can use dispose method.

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();
发布评论

评论列表(0)

  1. 暂无评论