1
votes

I am looking for a way to setup a callback function which will be invoked after every observable in every ViewModel.

Something similar to ajaxSend and ajaxComplete with jquery where a function will be called after each ajax call.

After looking for something like this in knockout, I found only few things: explicitly subscribing to observables and using computed observables. Neither of these things solves my problem, because I have a lot of ViewModels and therefore using this way I will be forced duplicate code in every ViewModel.

Is there a way in knockout to subscribe to the change of any observable in any model?

1

1 Answers

1
votes

You could try to do something like this:

1) Create function, that you want to be called when any observable in any viewModel changed (first parameter - value, second - event type, the same as in subscribe function third parameter):

function extendNotification(valueToNotify, event) {
    if (event != "beforeChange") {
        console.log("extend notification: " + valueToNotify);
    }
};

2) Create helper wrapper:

function beforeWrapper(fnBefore, fnOriginal) {
    return function () {
        fnBefore.apply(this, arguments);
        return fnOriginal.apply(this, arguments);
    };
};

3) And wrap ko.subscribable.fn.notifySubscribers function with your extender:

ko.subscribable.fn.notifySubscribers =
    beforeWrapper(extendNotification, ko.subscribable.fn.notifySubscribers);

May be it is not the best solution for your problem, but you could modify it if you want.
Demo Fiddle.