Pages

Thursday, July 28, 2016

Learning Meteor.js [Part 40]: Create document to insert using a Knockout view model

My previous post described how to use knockout.js within a meteor template. Once the form is built and data bound to the view model we can now grab the data and issue a request to insert a new recipe. Since both blaze and knockout can co-exist you can use either approach to wire events. I decided to use knockout since I find it easier to work with, so the HTML looks like this:
<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.