Knockout-2.2.0, subscribe get value before change AND new value

Abe picture Abe · Dec 29, 2012 · Viewed 13.6k times · Source

jsfiddle link: http://jsfiddle.net/T8ee7/

When I call Knockout's subscribe method is there a way I can get both the previous and new value? Right now, I can only call get these values separately. I want to trigger some code if the old and new value are different.

I suppose I could do the following, but it can get messy... (http://jsfiddle.net/MV3fN/)

var sv = sv || {};
sv.PagedRequest = function (pageNumber, pageSize) {
    this.pageNumber = ko.observable(pageNumber || 1);
    this.numberOfPages = ko.observable(1);
    this.pageSize = ko.observable(pageSize || sv.DefaultPageSize);
};


var _pagedRequest = new sv.PagedRequest();
var oldValue;
_pagedRequest.pageNumber.subscribe(function (previousValue) {
    console.log("old: " + previousValue);
    oldValue = previousValue;
}, _pagedRequest, "beforeChange");


_pagedRequest.pageNumber.subscribe(function (newValue) {

    console.log("new: " + newValue);
    if (oldValue != newValue) {
        console.log("value changed!");
    }

});

_pagedRequest.pageNumber(10);
_pagedRequest.pageNumber(20);
​

Answer

Nathan picture Nathan · Aug 1, 2013

I prefer using an observable extender.

http://jsfiddle.net/neonms92/xybGG/

Extender:

ko.extenders.withPrevious = function (target) {
    // Define new properties for previous value and whether it's changed
    target.previous = ko.observable();
    target.changed = ko.computed(function () { return target() !== target.previous(); });

    // Subscribe to observable to update previous, before change.
    target.subscribe(function (v) {
        target.previous(v);
    }, null, 'beforeChange');

    // Return modified observable
    return target;
}

Example Usage:

// Define observable using 'withPrevious' extension
self.hours = ko.observable().extend({ withPrevious: 1 });

// Subscribe to observable like normal
self.hours.subscribe(function () {
    if (!self.hours.changed()) return; // Cancel if value hasn't changed
    print('Hours changed from ' + self.hours.previous() + ' to ' + self.hours());
});