Change/update Handlebars JS 中来自循环内父上下文的变量

Change/update a variable in Handlebars JS from the parent context inside a loop

我看过很多关于如何访问 属于循环内父上下文的变量的示例。但是,我不仅需要访问该变量,还需要 change/update 它。

正如您在下面看到的,我有一个设置变量的自定义助手,但是当我尝试在循环内更改该变量时,它不起作用。有什么办法让它起作用吗?

请看这个jsFiddle.

模板

{{setVarWithName "test" "hello"}}
{{#each questions}}
    <h3>{{title}}</h3>
    <p>before update: {{../test}}</p>
    {{setVarWithName "test" "goodbye"}}
    <p>after update: {{../test}}</p>
    <hr />
{{/each}}

Handlebars init with helper

var source = $("#template").html(); 
var template = Handlebars.compile(source); 

var data = {
  "questions": [
     {"title": "Question 1"},
     {"title": "Question 2"}
   ]
}; 

Handlebars.registerHelper('setVarWithName', function (name, value) {
    this[name] = value;
    return '';
});

$('body').append(template(data));

答案,就像 JavaScript 中经常出现的那样,就是范围。基本上,当在 {{#each}} 循环内部使用时,您的助手 setVarWithName 内部的 this 不会指向您的 data 变量,但它确实指向 question[@index]。您需要做什么:

var source = $("#template").html(); 
var template = Handlebars.compile(source); 

var data = {
  "questions": [
     {"title": "Question 1"},
     {"title": "Question 2"}
   ]
}; 

Handlebars.registerHelper('setVarWithName', function (name, value) {
    data[name] = value; // changed from this to data
    return '';
});

$('body').append(template(data));

看我的作品fiddle。为了便于阅读,我添加了 {{s}} 帮助程序以将呈现的 this 打印到模板中。