Quantcast
Channel:
Viewing all articles
Browse latest Browse all 27

Unwritten help for Tempo.js

$
0
0

Tempo.js is a templating library for HTML (in javascript) that uses JSON to smartly populate the HTML. This makes it great for doing things such as having a file that you use to localize your app.
There are probably actual localization libraries for just for JS. I don’t care.

When I used Tempo.js today, there were a few things that threw me off, and I found the site’s page which acts as its only documentation to be lacking. (It’s great to show me a lot of cool features, but sometimes you want a realistic and simple hello-world that doesn’t cram everything your library can do in one place)


  • When you pass an object to Tempo, it should be the parent container of the object / objects you wish to templatize.
  • When you pass in an object, make sure it is the actual object (not a jquery object, although it claims to accept them so this is a bug)
  • Here is an example of a snippet from my HTML file:

    <div class="bigCotnainer">
      <div data-template="data-template" >{{instructions}}</div>
    </div>

    Here is an example of my JSON file
    (I love comments / commenting, so I like to put my JSON comments in a node called _COMMENTS)

    [
      {
        "_COMMENT" : "PERFORMANCE CALCULATOR",
        "selector": ".bigContainer",
        "data": {
          "instructions": "Explore the interactive chart to see how the fund has performed during key points of market volatility."
        }
      }
    ]

    As you can see, I have my selector set as .bigContainer not the object with the actual template stub! I like to my strings in a separate file which makes sense, but keep all of that mess inside that file and leave it out of your code.

    Ideally I would like to just run Tempo.js on page init and be done with it.
    Well my solution was to make my JSON container an array of objects, where each object has a selector and a data object. If you have that you can then do something like this:

    $.get( url, function ( dataString ) {
      var data = JSON.parse( dataString );
      for ( var i = 0; i < data.length; i++ ) {
        Tempo.prepare( $( data[i].selector )[0] ).render( data[i].data );
      }
    } ;

    (I used Jquery in the above example. I hate jquery, don’t use it if you can avoid it which is often!)
    That will parse your strings file, and find the given ‘selector’ and render it with the accompanying data for each object in your root array.
    If you use the _COMMENT tag, these things combined are a very pretty way to keep web-app organized.


    Viewing all articles
    Browse latest Browse all 27

    Trending Articles