2

Lets say I have name = ko.observable('John') that is bind to the input as value. I need to show (hidden before) <button>Save</button> if name get changed. So if I edit name from John to Jack then save button should appear and if edit back to John it should hide again. Have you any ideas of what kind of binding/extension can be applied here?
Great thanks!

John Papa
  • 21,880
  • 4
  • 61
  • 60
Sergey Metlov
  • 25,747
  • 28
  • 93
  • 153

1 Answers1

3

What you need is called dirty tracking.

There is a ko plugin called KoLite which contains a dirty flag implementation (you can read about how it works in this article):

The usage is very simple you just need to pass your obserables into the ko.DirtyFlag (this will return computed observable) method:

var ViewModel = function() {
    var self = this;
    self.name = ko.observable('John');
    self.dirtyFlag = new ko.DirtyFlag(self.name);
}

And in your view you can bind to the isDirty property on your dirtyFlag:

<input type="text" data-bind="value: name, valueUpdate: 'keyup'"/>
<div data-bind="if: dirtyFlag().isDirty">
    <button>Save</button>
</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

Demo fiddle.

nemesv
  • 138,284
  • 16
  • 416
  • 359