June 16, 2014

Handlebars


Handlebars is a JavaScript templating engine that extends mustache (a logic-less templating engine) functionalities by adding a minimal logic.
It allows developer to:
  • compile the template
  • use :
o   a minimal logic ( #if ,#unless,#with,#list,#each)
o   helpers ( invoke JavaScript function {{ function_name arg1 arg2 …}}
o   {{this}}
o   Handelbars.SAfeString()

How to use HandelBar: a basic example

       -  Add the Handlebars library (download it from http://handlebarsjs.com/)
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.rc.1/handlebars.min.js"></script>

-  Write your template

 <script id="myTemplate" type="text/x-handlebars-template">
     <h1>{{article }}</h1>
     </script>

- Call your template by using JavaScript
o Compile your template
 var template = Handlebars.compile($("#myTemplate").html());

o Define a context
var conext = {article: "Test"} ;

o Set the value of “inner Html” of a div ( for example) by the html rendered value from the template      
            $("#placeholder").html (template (conext));


 Finally we ll get the example below :

<!DOCTYPE html>
<html>
<head>
   <title>Handlebars.js example</title>
</head>
<body>
   <div id="placeholder">
       This will get replaced by handlebars.js</div>
   <script type="text/javascript" src="Js/handlebars.min.js"></script>
   <script type="text/javascript" src="Js/jquery-1.11.1.min.js"></script>
   <script id="myTemplate" type="text/x-handlebars-template">
   <h1>{{article }}</h1>
   </script>
   <script type="text/javascript">
       var template = Handlebars.compile($("#myTemplate").html());
       var conext = {           
           article: "Test",
       };
       $("#placeholder").html(template(conext));
   </script>
</body>
</html>

Classical Inheritance in JavaScript


By using prototype and constructor properties, inheritance in Javascript is possible.
The prototype property allows you to add properties and methods to an object.

Example  


function Person(theName, theEmail) {
    this.name = theName;
    this.email = theEmail;
}
Person.prototype = {
    constructor: Person,
    changeEmail: function (newEmail) {
        this.email = newEmail;
        return "New Email Saved: " + this.email;
    }
};

function User() {
    this.quizScores = [];
    this.currentScore = 0;

}
User.prototype = new Person("", "");
User.prototype.constructor = User;
User.prototype.saveScore = function (theScoreToAdd) {
 this.quizScores.push(theScoreToAdd);
User.prototype.showNameAndScores = function () {

    var scores = this.quizScores.length > 0 ? this.quizScores.join(",") : "No Scores Yet";
    return this.name + " Scores: " + scores;
};

How to use it

user = new User();
user.changeEmail("test@noserver.net");

The result is the value of the inherited property "email"  is "test@noserver.net";