Javascript

Handlebars js

I have recently begun using handlebars js for my various jquery mobile apps. This has been a great experience and here i will try to explain why and how i have used it. I will also include extensions and plugins which i have used to handle the development.

The challenge has been entering dynamic content into lists or as changes based on user actions, and often the html for the dynamic content would be entered as strings in the javascript. But a solution for this is using a templating system like handlebars. It allows you to define templates in <script/> tags which can then be referenced in your code when you need dynamic content.

For my projects I prefere not to have my templates in <script/> tags so I found several solutions which allowed me to make separate template files. For my projects I used sync_async_loading_handlebars which is a very simple script but it handles the task really well. Using jquery mobile i found that I got the best performance if I preloaded the templates using the T.prefetch function. This loads the template data into a cache object from where it can easily be referenced later on.

Using sync_async_loading_handlebars i then entered dynamic content by creating a data object and calling T.render, as follows:

var themeData = { 
  title: 'test', 
  src: 'data', 
  class: 'some class' 
}; 
T.render('testTemplateItem', function(t) { $('.target').append(t(themeData)); }); 

My template would then look something like this.

<div class="{{class}}">
  {{#if src}}
  <div class="image-container"><img src="{{src}}" /></div>
  {{/if}}
  <h2>{{title}}</h2>
</div>

I also found a library of handlebars extensions which are very handy. The people behind swag have composed a library of extensions which contain most of the theming functionality you could possibly want and then some.

 

 

Hopscotch tour js

I had to include some help text for a mobile app i am developing and maintaining and for this we decided to use a tour script because it would allow us to keep the screen clear of static description text and at the same time give a smooth intoduction to the elements which needed explanations.

I tested out several scripts like joyride and pageguide, but found that the one which worked best with jquery mobile was hopscotch js. It allows lots of configuration and you configure the tours in json, which keeps the html of the app clean.

Subscribe to Javascript