Skip to content

Instantly share code, notes, and snippets.

@mblarsen
Created July 20, 2016 06:31
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mblarsen/30ff1f5c1adf215179b0046515f86e45 to your computer and use it in GitHub Desktop.
Save mblarsen/30ff1f5c1adf215179b0046515f86e45 to your computer and use it in GitHub Desktop.
/**
* Knockout.js extension that gives both new and old value to
* subscription functions.
*
* Credit: http://stackoverflow.com/a/18184016/204610
*
* Changed JBeagle's code to return a disposable subscription
* object so it conforms to subscribe()
*/
ko.subscribable.fn.subscribeChanged = function (callback) {
var oldValue;
var oldSubscription;
var newSubscription;
oldSubscription = this.subscribe(function (_oldValue) {
oldValue = _oldValue;
}, this, 'beforeChange');
newSubscription = this.subscribe(function (newValue) {
callback(newValue, oldValue);
});
return {
oldSubscription: oldSubscription,
newSubscription: newSubscription,
dispose: function () {
this.oldSubscription.dispose()
this.newSubscription.dispose()
}
}
};
@mblarsen
Copy link
Author

Shorter version by @mbest not relying on beforeChange

ko.subscribable.fn.subscribeChanged = function (callback) {
    var savedValue = this.peek();
    return this.subscribe(function (latestValue) {
        var oldValue = savedValue;
        savedValue = latestValue;
        callback(latestValue, oldValue);
    });
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment