Knockout doesn't provide any way to extend a subscription. But you could wrap the subscribe
method to provide a way to do so. Here's an example:
ko.subscribable.fn.subscribe = (function (originalFunction) {
return function (callback, callbackTarget, event) {
var boundCallback = callbackTarget ? callback.bind(callbackTarget) : callback,
currentCallback = boundCallback,
passthroughCallback = function (value) { currentCallback(value) },
subscription = originalFunction.call(this, passthroughCallback, null, event);
subscription.extend = function (newCallback) {
currentCallback = newCallback.bind(null, currentCallback);
};
return subscription;
}
})(ko.subscribable.fn.subscribe);
http://jsfiddle.net/mbest/LKrr9/
You also mention being able to retrieve a subscription from an observable later on. You might accomplish that by adding a line in the function above like this:
this.latestSubscription = subscription;
This assumes that subscriptions won't be disposed. If you want to get the latest non-disposed subscription, it'll be a bit more complicated.
NOTE: The above method of extending subscribe
only works in Knockout >=3.1.0. For prior versions, you've have to attach the new subscribe
method in an extender.