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
return function(context, options) {
if (!compiled) {
compiled = compileInput();
}
return compiled.call(this, context, options);
};
Why does the scope change and is there a workaround?
user1834464