kyrisu kyrisu - 12 days ago 6
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

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) {
                fired=true;
                target(newValue);
            }
        }
    });
    result(target());
    return result;
};

then use it as follows:

var myObservable = ko.Observable(blah).extend({fireOnce:null});