JSFiddle - React, Tailwind, and code Playground
HTML
<script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/2.3.0/knockout-min.js"></script>
<div>
</div>
JavaScript
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;
}
// Define observable using 'withPrevious' extension
var hours = ko.observable(1).extend({ withPrevious: 1 });
// Subscribe to observable like normal
hours.subscribe(function () {
if (!hours.changed()) return; // Cancel if value hasn't changed
var message = 'Hours changed from ' + hours.previous() + ' to ' + hours();
$('div').append('<span>' + message + '</span><br/>');
});
// Change hours a couple of times
console.log(hours(2));
console.log(hours(3));
console.log(hours(3)); // Ignored because hours.changed() will return false
console.log(hours(4));