javascript - 从循环内的父上下文更改/更新 Handlebars JS 中的变量

标签 javascript jquery html handlebars.js handlebarshelper

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

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

请看这个 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 中经常出现的那样,答案是作用域。基本上,this在你的助手里面 setVarWithName没有指向你的 data{{#each}} 中使用时的变量循环,但它确实指向 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放入模板中以提高可读性。

关于javascript - 从循环内的父上下文更改/更新 Handlebars JS 中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48505033/

相关文章:

javascript - 正则表达式对javascript有帮助吗?

javascript - JavaScript 中的竞争条件与复合赋值

html - 是否有可能使文本溢出 :ellipsis for select with css only?

javascript - jQuery 鼠标悬停/鼠标悬停显示/隐藏 div

html - 带有 CSS 梯形形状按钮的阴影

javascript - Chrome 扩展中的CORS

javascript - 使用 express.js 在 POST 上提供静态内容

javascript - 如何使用 jQuery 禁用多个链接?

javascript - 检查 div 的长度(不包括空格)

javascript - 为什么当用户点击太快时 jQuery Mobile Simple Dialogue 会卡住?