I was working on a project which uses KnockoutJS and had the need to implement the idea of setting a dirty flag if a user made a change to a form, this would in turn enable a save button and allow the changes to be saved.
KoLite makes this very easy indeed, I decided to put together some quick code demonstrating the features I mention – at work jsfiddle.net doesn’t work too well so I have added the code to a sample app and uploaded it to GitHub.
The original samples and more information can be found here, I thought they could do with being expanded upon a little.
The ViewModel I used for the demo code is as follows:-
Dirty Flag and how to use it
- The code on line 10 is creating the dirtyflag by using KoLite’s DirtyFlag – I pass in which observable’s I want to monitor to see if they become dirty when they’re value changes.
- The code on line 27 is setting up a computed observable which will return true if the observables have theyre values changed, otherwise it will return false.
So by having some observables updated we can track for dirty changes and then decide what we want to do on our form, an example would be to enable the clear form button as well as enable the save button on when we have the dirty flag set to true.
Grey out button when Ajax request is in progress
- The code on lines 29-33 is making use of the KoLite asyncCommand
- If you then add the code below, to the html then we have the functionality were after.
Grey out button when Ajax request is in progress and show activity icon
- If you add in the extra binding like so:- [sourcecode language=”csharp”] <button data-bind="command: saveCommand, activity: saveCommand.isExecuting">Save</button>
KoLite will now add in an activity icon within the button, and that’s it – in the example code I am using an Ajax post to call the MVC Controller and whilst this is off doing work the activity icon spins.
Leave a comment after the beep.