Using Blaze templates in Tizen

Introduction

Every complex application written in JavaScript should use a MVC pattern. Not using this or similar pattern can make your code not reusable and hard to read, investigate and fix. There are many good MVC frameworks that do their job. In this article I'm going to describe how to work with the Blaze templating engine which is not a standard template system. It provides not only template separation from the application's logic but also great data binding. Data binding is the process of binding application's model data with the view, so every change to the data is reflected in the application's UI. Thanks to this you don't have to update the UI manually. You just set proper bindings and everything starts to work out of the box. This kind of programming is called "Reactive Programming".

The Blaze templating engine

The Blaze templating engine is one of the packages of the Meteor JavaScript framework/platform. Meteor is a great tool for creating JavaScript applications with JavaScript as a main programming language on both the client and the server. You just write one code that works the same in both environments. Meteor is not only a framework but also a platform. Platform in this situation means server application, package system and whole environment that helps you create applications. You can write entire application just by using the Meteor platform.

Blaze is not just an another templating engine. It's syntax is based on Handlebars but it was rewritten and extended. The Blaze templating language is named Spacebars. In contrast to Handlebars, Blaze doesn't rerender the whole template every time the data changes. It's intelligent enough to determine what elements of the UI need refreshing and only those will be recreated. It's so intelligent that even if you are typing in the input field and parent elements need rerendering it doesn't interrupt you. It will just make sure that your input is not affected. Moreover if only some attribute changed it doesn't need to rerender the entire DOM element, it will make proper changes to the given attribute only. The same is valid if it goes about inline CSS styles. The Blaze templating engine is not a small library but it's super fast and a lot easier to work with than for example Angular which provides similar functionality. It makes Blaze a really good templating engine also for such devices like the Gear smart watches which have smaller computation power.

Full documentation of Blaze can be found under this address http://meteor.github.io/blaze/docs.html.

Preparation

In order to use Blaze we have to go to the official GitHub repository and download uncompressed or compressed version. Now, we have to attach the library to our index.html file.

<body>
  <!-- Your code here -->
  
  <script src="js/lib/blaze.js"></script>
  <script src="js/main.js"></script>
</body>

As you can see, we've attached it at the end of the BODY tag to make sure that it will be run when all the content of the website is loaded.

Defining templates

We have to define templates within our BODY tag inside SCRIPT elements. Each template should have proper type and defined name. Let's see the example code.

<body>
    <script type="text/spacebars" name="main">
        <div>Hello {{name}}!</div>
    </script>
    
    <script src="js/lib/blaze.js"></script>
    <script src="js/main.js"></script>
</body>

As you can see we've named our template main. It's a default name for the main template, which will be put inside the BODY element after initialization. Inside our template we've defined one DIV element with the content Hello {{name}}!. It's the same syntax like in the Handlebars templates. {{name}} just tells the template engine to render value of the name variable in this place. We will discuss in next sections how to set this variable's value.

We can include one template inside another one just by using syntax from Handlebars for including partials {{> templateNameToInclude}}. However in Blaze, we don't have to register a partial. We can just include any template we want.

<script type="text/spacebars" name="person">
    <li>Name: {{name}}</li>
</script>

<script type="text/spacebars" name="main">
    {{#each people}}
    <ul>{{> person}}</ul>
    {{/each}}
</script>

As you can see, we've used another Handlebars expression, each function which loops over given collection. For each record of people collection we are including a person template that renders particular person's details.

Filling template with data

To pass some data to the template we have to define helpers on this template.

Template.main.helpers({
    name: function () {
        return 'John';
    }
});

As you can see we've defined an object and passed it to the helpers() function. Each attribute of this object will be a variable name inside the template. Now after running the application, the main template will be rendered with the text Hello John!.

Reactive data source

Ok, we have a template with the data but we would like it to be reactive. The template should dynamically rerender whenever the data changes. To do this, we have to use Blaze.Var reactive data source or just create our own. Blaze.Var is the simplest possible reactive data source. Every value set on it is serialized (stringified) and compared with the previously stringified value. If strings are the same nothing happens. Otherwise the process of template invalidation will start. Only templates that depend on given reactive data source will be rerendered and as it was written earlier only parts of the template that need rerendering will be replaced with its new version. Let's see how to create the simplest reactive data source instance.

var stringData = new Blaze.Var('some text value');
var numberData = new Blaze.Var(123);
var booleanData = new Blaze.Var(true);

Using Blaze.Var constructor we can pass an optional parameter which will be a default variable value. Let's see how to set and get a value from this reactive data source.

var data = new Blaze.Var(0);

data.get(); // 0
data.set(123); // Templates invalidation

And let's use it in the template's helper.

var name = new Blaze.Var('');

Template.main.helpers({
    name: function getName () {
        return name.get();
    }
});

It couldn't be easier. But how exactly Blaze knows that changes to the name object should cause template invalidation? It's the job of the helpers() function. It takes an object passed as a first parameter and creates a new computation for this template. Now every use of the reactive data source creates new dependency correlated with the given computation. Now when we set a new value in the reactive data source it invalidates dependency which causes reexcution of the getName() function. You don't have to understand the whole process to use it but it's good to get familiar with it if you want to use more advanced Blaze features or create your own reactive data sources.

You can also find more advanced reactive data sources that are shipped with Blaze as the MiniMongo package. It's a simplified Mongo database that runs in the client browser and provides most of the MongoDB functionality and it's reactive! You can try it out using the Package.minimongo.LocalCollection constructor. We're not gonna focus on using it right now. We will dedicate a separate article for that subject.

Binding events to a reactive data source

You may want to do one more thing, binding some events with reactive data source so you wouldn't have to set a variable value by hand, but for example take data from an input field and update the template while typing in the input. Let's consider the given template and see how to bind events to the data source.

<script type="text/spacebars" name="main">
    <input type="text" />
    <div>Hello {{name}}!</div>
</script>

 

var name = new Blaze.Var('');

Template.main.helpers({
    name: function getName () {
        return name.get();
    }
});

Template.main.events({
    'keyup input': function setName (e) {
        name.set(e.currentTarget.value);
    }
});

We've added an input field to our template and added an event object to it using the events() method of the Blaze template. The events object is a simple key - value pair object, where key is the event name and css selector, and value is the event handler function. So we listen to the keyup events on the input field and then set the value of our reactive data source.

Sample application

You can download the sample application attached to this article that demonstrates how to use Blaze. It's not a very complex application, but it shows the basic features.


Sample application screenshot

We're not gonna describe the sample application in this article because we've already featured the most important parts of it. You can download the application and investigate it by yourself. After reading this article the whole application's code should look familiar to you.

Summary

This article is just an introduction to the Blaze templating engine. We encourage you to read more about it on the official website.

File attachments: