Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create knockout observable subscription that fires only once?

In my model I have a property that is loaded asynchronously. I want it to generate another model property after it loads.

I was thinking about subscription that could fire after the 1st property changes, generates the 2nd property and then get disposed - I don't know how can I dispose subscription from inside itself.

Is there a way to fire one time event after observable property changes?

like image 527
kyrisu Avatar asked Dec 04 '12 11:12

kyrisu


People also ask

How do I set observable value in Knockout?

To create an observable, assign the ko. observable function to the variable. A default value can be specified in the constructor of the call. Knockout then converts your variable into a function and tracks when the value changes, in order to notify the UI elements associated with the variable.

How do you clear observable in Knockout?

It can be like this. var model = { "xId": ko. observable(0), "xName": ko. observable(null), "Type": ko.

What is applyBindings in Knockout?

To apply bindings for the whole HTML document, it can be done using the Knockout function applyBindings() with passing the view model as the first and the only parameter: ko. applyBindings(viewModel); To apply Knockout for a part of the HTML document, pass the DOM element as a second parameter: ko.

What is KnockoutObservable?

When you subscribe to KnockoutObservable<string[]> , then you will receive a string array ( string[] ) The other one is an array of observables ( KnockoutObservable<string> ), each one resolving to a result with a type string. When you wish to receive the string array, you should use KnockoutObservable<string[]>


1 Answers

To dispose subscription from inside itself just create reference to it:

var subscription = yourObservable.subscribe(function (newValue) {
    ...
    subsription.dispose();
});

If you don't want to write this code every time, you can extend observable with new method:

ko.subscribable.fn.subscribeOnce = function (handler, owner, eventName) {
    var subscription = this.subscribe(function (newValue) {
        subscription.dispose();
        handler(newValue);
    }, owner, eventName);
    return subscription;
};

...

// usage
var subscription = yourObservable.subsribeOnce(yourHandler);

And dont' forget to dispose subscription on component disposal in case it was not fired.

like image 188
blazkovicz Avatar answered Nov 15 '22 04:11

blazkovicz