Friday, October 5, 2012

Cancel button for KnockOut form


I recently built a dynamic form using KnockOut.
This is how that page worked:

A user selectes a person from a list, an AJAX request will post the person id to the server which will then return  a JSON object of that person info (phone, name, age...) I didn't know which info will come back for that person. this is why the form is dynamic. anyway I decided to use a data-bind of template (there were a few a kinds of fields not just text boxes) so template with jQuery templates created a very cool dynamic form.

Now a new demand came saying I should add a cancel button to the form. after a quick Google search I came across this post: guarding your model in a very very good blog for KnockOut knockmeout.net,
anyway accepting changed for a specific observable is nice.. but didn't fit my needs for a full form cancel button. so I decided to go with a simple solution. I will keep my original native JSON object that came back from my AJAX request!

so it will go something like this:


// callback function from server
function AjaxCallback (model) {
   // page is a namespace 
   var tempModel = {};
   // important making a new object (tempModel) so 
   // the copyModel won't be a reference
   $.extend(tempModel, model);
   page.copyModel = tempModel; 
   UpdateModel (model);
function SwitchModel (modelJSON) {
   ko.mapping.fromJS(page.copyOfModel, {}, page.model);
   // we will need to apply the bindings again so the view will update.
   ko.applyBindings(page.model);
}
function CancelChange () {
   UpdatehModel (page.copyModel);
}

function SavePerson () {
   var jsonModel = ko.mapping.toJS(page.model);

   // ------- save the person through ajax

   // don't forget to update the copy model so if 
   // the cancel button will be
   // clicked the last changes won't disappear.. so:
   // better if placed in the success callback of the ajax request
   page.copyModel = jsonModel;
}


page.model is a model i assume you already have on your page. I only gave to parts of the code needed for a cancel button.

And that's pretty much it...very simple but effective way to create a cancel button
for the whole KnockOut form

No comments:

Post a Comment