<button class="btn btn-primary recipe-update" data-bind="click: update">Save</button>
The view model handles the event and invokes the server method:
import { RecipeSchema } from '../../api/recipes/recipes.js'; function RecipeViewModel() { var self = this; self.name = ko.observable(); self.update = function() { var recipe = ko.toJS(self); RecipeSchema.clean(recipe); var validationContext = RecipeSchema.namedContext(); if(!validationContext.validate(recipe)) { var errorObj = validationContext.getErrorObject(); postal.publish({ topic: 'toast', data: { error: errorObj, message: errorObj.message } }); } else { RecipeMethods.addOrUpdate.call({ recipe: recipe}, function(err) { if (err) { postal.publish({ topic: 'toast', data: { error: err }}); } }); } } }
Things to note:
- First the view model is turned into a regular javascript object by using ko.toJS().
- Then, a schema is used to clean the object and run validation. See my previous post about data cleaning.
- If there are errors an event is raised so that the application shows an error UI.
- If there are no errors the server method is called (an error event is also raised if the call fails).
Visit the live demo or view the soure code.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.