BorisMoore / jquery-tmpl

The original official jQuery Templates plugin. This project was maintained by the jQuery team as an official jQuery plugin. It is no longer in active development, and has been superseded by JsRender.
3.23k stars 1.01k forks source link

Question: Function expressions and `this` #65

Open gregerolsson opened 13 years ago

gregerolsson commented 13 years ago

(sorry for the long question)

I was looking at the plugin code and the docs and I was curious about the reasoning behind the use of $data and $item together with expressions that evaluate to functions. Consider the following template:

<article class="ticket">
  <h1>${title}</h1>
</article>

where the data passed to the template is an object with properties of both function type and primitive types:

$('#template').tmpl(aTicketObject);

If the expression title evaluates to a function, the function detector in buildTmplFn() will notice that and call the function using $item as this (if it is a "primitive" it will just use its value).

This forces either my title() function in the "ticket" object to know about the templating system and use this.data to get to its "true" this, or it forces my template to this:

<h1>${$data.title}</h1>   or   <h1>${$data.title()}</h1>

I can also put my object in a wrapper and use the wrapper property to access it:

$('#template').tmpl({ticket: aTicketObject});
  ..and then this works..
<h1>${ticket.title()}</h1>
  ..but not this..
<h1>${ticket.title}</h1>

So my actual question is, what is the reason that function expressions are called with $item as this (which feels leaky) and not with $data?

Thanks!

jzaefferer commented 13 years ago

Its very likely that the automatic function invokations will get removed, making an explicit call necessary while removing problems like this. The context would then be the object containing the function

gregerolsson commented 13 years ago

Ah, good to know, thanks for the reply.

BorisMoore commented 13 years ago

Yes this relates to the issue on nje/jquery-tmpl: https://github.com/nje/jquery-tmpl/issues/issue/29. I'm keeping this issue open. As Joern says, we expect to make some design changes that will address this in a Beta2 release, probably in April. Keeping this issue open, for tracking.

rdworth commented 13 years ago

Thanks for taking the time to submit this issue. Just wanted to let you know this plugin is no longer being actively developed or maintained by the jQuery team. See README for more info.