kyrisu kyrisu - 1 year ago 93
Javascript Question

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?

Answer Source

You could write an extender to suppress all but the first firing:

ko.extenders.fireOnce= function(target) {
    var fired=false;
    var result = ko.computed({
        read: target,
        write: function(newValue) {
            var current = target();
            if (newValue!== current && !fired) {
    return result;

then use it as follows:

var myObservable = ko.Observable(blah).extend({fireOnce:null});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download