Pages

Friday, July 22, 2016

Learning Meteor.js [Part 39]: Use knockout.js on blaze templates

The next thing to tackle is create, update and delete recipes. Since the recipe document has many more fields and nested documents in arrays I thought it would be simpler to write the edit form using a library that supports two-way data binding, like knockout.js. Let's see what it takes to integrate it into a meteor app.

There a number of knockout packages in atmosphere, some attempt to create a bridge between knockout observable's and meteor's reactive collections. I didn't want any of that fanciness, so I just installed it as a regular npm package. Then, import it on the template that needs it and call ko.applyBindings during onRender:
import ko from 'knockout';

function RecipeViewModel() {
    this.name = ko.observable();
    this.serves = ko.observable();
    this.sourceUrl = ko.observable();
    this.imageUrl = ko.observable();
    this.author = ko.observable();
    this.directions = ko.observableArray([]);
    this.ingredients = ko.observableArray([]);
}

Template.recipeEditPart.onRendered(function() {
    this.viewModel = new RecipeViewModel();
    ko.applyBindings(this.viewModel, this.find('.recipeEditPart'));
});

Now, you can use knockout's data-bind attributes on the markup.
<template name="recipeEditPart">
<div class="recipeEditPart">
        <div class="row">
            <label class="col-sm-2 control-label">Name</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" placeholder="Name" data-bind="textInput: name">
            </div>
        </div>
</div>
</template>

Remember to call ko.cleanNode on the template's onDestroyed event. One nice thing about using knockout with meteor is that you can mix blaze's handlebar syntax with knockout data-bind syntax on the same view. Now we are ready to implement the CRUD operations.

You can check the code up to this point by using this commit or visit the live demo.

2 comments:

  1. hi

    is aldeed:autoform different from knockout for what you are doing?

    ReplyDelete
  2. I have not used autoform so I can't comment or compare them.

    ReplyDelete

Note: Only a member of this blog may post a comment.