Why does Handlebars change the amount of data we transfer?

Say I have the following "class":

function Person( firstname, lastname ) {
   this.attributes = {};
   this.attributes.name = firstname + ' ' + lastname;
}

Person.prototype.name = function() {
  return this.attributes.name;
};

When I pass this object to the visualizer

var myPerson = new Person( "Bob", "Robert" );

var template = Handlebars.compile( "<div>{{person.name}}</div>" );

var data = {person: myPerson, courseName: "LOG210"}

template( data );

The problem is that the this keyword in the above function is no longer bound to the Person instance. Instead, it is tied to data that is passed to Handlebars.

For example, when handlebars calls the data.person.name () function , the scope of the this variable in this.attributes.name is object data ( {person: myPerson, courseName: "LOG210"} ), not the myPerson object.

The reason apparently lies in handlebars-v1.3.0

// Template is only compiled on first use and cached after that point.
return function(context, options) {
  if (!compiled) {
    compiled = compileInput();
  }
  return compiled.call(this, context, options);
};

Why does the scope change and is there a workaround?

+4
1

, .

( ), . ( ).

Handlebars.registerHelper('ct', function(obj, fn) {
  return obj[fn]();
});

var template = Handlebars.compile( "<div>{{ct person 'name'}}</div>" );

http://jsfiddle.net/dp54p/

+1

All Articles