Platypus Header

Platypus Innovation Blog

Showing posts with label js. Show all posts
Showing posts with label js. Show all posts

6 May 2014

Javascript/html templating: underscore.js for the win


Man cutting steel with a template (cc) Washinton State Dept of Transport
After experimenting with Javascript templating libraries, we decided to use underscore.js. It scores over JQuery, Moustache and others in having a very clean and simple relationship between templating and normal code.

Underscore templates provide spaces where you can drop into javascript code - that's all they do, but it works better than trying to do more. Crucially, this gives you a lot of freedom - the full freedom of javascript.

For example, here is a simple loop using underscore:


       <% for(var i=0; i<3; i++print("
  • Line "
  • +i+"
    "); %>

    That middle section isn't the prettiest, but it's something every web developer should already understand -- and know how to write.

    Compare this with the approach taken in JQuery templates:


         {{each}}
            
    • Line $i

    •    {{/each}}


      This looks a little bit nicer -- but what are these new magic {{}} tags? Plus we need to pass in the list `[{i:1},{i:2},{i:3}]` in order to use it. And we have less ability to build richer more complex templates.

      Hence, by taking a simpler code-based approach, underscore.js templates actually end up being more widely editable and more powerful.

      10 February 2014

      Javascript Enums

      Enums are a useful way to handle a set of constants. They protect against typos and bad-values, help to spot missed cases, and make refactoring a lot safer.

      Javascript does not have enums. So how can we get the same benefits?

      Enum.js is a simple class which gives you enum-like behaviour.

      Example: Instead of writing e.g. if (sibling == 'BROTHER') ... throughout your code, write Sibling = new Enum('BROTHER SISTER'); then use if (Sibling.isBROTHER(x)) ....

      Here's the Enum.js code as a gist

      Good-Loop Unit