KO Dirty Extender
by Casey Webb
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script>
Babel + JSX
ko.extenders.dirty = function(obs) {
const initVal = _.clone(obs())
obs.isDirty = ko.pureComputed(() => {
if (_.isPlainObject(initVal) || _.isArray(initVal))
return !_.matches(initVal)(obs())
else
return initVal !== obs()
})
return obs
}
const foo = ko.observable('foo')
foo.extend({ dirty: true })
alert(foo.isDirty())
foo('bar')
alert(foo.isDirty())
foo.extend({ dirty: true })
alert(foo.isDirty())
foo('foo')
alert(foo.isDirty())