what is the `this` in a compiled jst template

- 1 answer


When an ejs file compiles, it becomes a javascript function. For example, this ejs file

<h3> Users Index</h3>
  <% users.each(function (user) { %>
    <li><%= user.get("name") %></li>
  <% })%>

compiles to this javascript function:

(function() { this.JST || (this.JST = {}); this.JST["users/index"] =     function(obj){var __p=[],print=function(){__p.push.apply(__p,arguments);};with(obj||{}){__p.push('<h3> Users Index</h3>\n\n<ul>\n  ');  users.each(function (user) { ; __p.push('\n    <li>',  user.get("name") ,'</li>\n  ');  }); __p.push('\n</ul>\n\n');}return __p.join('');};

In the above javascript function, what does the this refer to? (ie. a backbone view, etc.)




If you run a self executing function construct like that

(function() { console.log(this) }).call(this);

You'll notice it'll output (Chrome console output)

Window {external: Object, chrome: Object, document: document, i: undefined, StackExchange: Object…}

So all this does is simply add the variable JST to the global (window) namespace so that it's accessible in every following script.

The line this.JST || (this.JST = {}); will make sure that if window.JST (window = this as we saw) exists and if not it gets created and it's value will be an empty object (this.JST = {}).

source: stackoverflow.com