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

this in {{each}} doesn't work #127

Closed Hoazl closed 13 years ago

Hoazl commented 13 years ago

The {{each}}-method does not preserve the same this-object as in the outer scope. For example, see this fiddle: http://jsfiddle.net/4JGhf/1/ I have a template with a subtemplate, and in the subtemplate I want to output the sorting-property of the parent template; Directly in the template, it works (${this.parent.data.sorting}), but in the each-loop I get the error "this.parent is undefined" in firebug.

So I made a small modification to the definition of the "each"-tag:

"each": {
    _default: { $2: "$index, $value" },
    open: "if($notnull_1){var $parent=this;$.each($1a,function($2){with(this){;",
    close: "}});}"
},

The important part here is "var $parent=this" which sets the $parent-variable to be accessible within the each-function. Now look at the second fiddle: http://jsfiddle.net/4JGhf/2/. Instead of using the ${this.parent.data.sorting}-value in the {{each}}-loop, I use the ${$parent.parent.data.sorting}-value to access the property, and it works!

BorisMoore commented 13 years ago

The intention was to use $item, rather than this, to get the current tmplItem. So it is not necessary to define a new $parent variable... Can you confirm that this works for you?

Parent's sorting: ${$item.parent.data.sorting}<br />
{{each $data.prices}}
    Parent's sorting in Each: ${$item.parent.data.sorting}<br />
Hoazl commented 13 years ago

Yes, it works when using $item. Thank you very much!