在主干视图中创建handlebar.registerHelper时,在哪里定义上下文(JSON对象)?
我不知道在主干视图的handlebar.registerHelper函数中在何处定义上下文(JSON对象) 当我通过$.getJSON访问助手函数数据时,我能够在控制台中呈现它,但我无法将助手函数中的数据获取到我的模板中: var SurveyView=Backbone.View.extend({在主干视图中创建handlebar.registerHelper时,在哪里定义上下文(JSON对象)?,json,backbone.js,handlebars.js,Json,Backbone.js,Handlebars.js,我不知道在主干视图的handlebar.registerHelper函数中在何处定义上下文(JSON对象) 当我通过$.getJSON访问助手函数数据时,我能够在控制台中呈现它,但我无法将助手函数中的数据获取到我的模板中: var SurveyView=Backbone.View.extend({ 模板:handlebar.compile( “”+ “{{#每个模型}}{{attributes.name}{{{attributes.question}”+ “{{{{answerList info
模板:handlebar.compile(
“”+
“{{#每个模型}}{{attributes.name}{{{attributes.question}”+
“- {{{{answerList info}}{{{{answerList}}{/answerList}
{{/each}”+
“
”+
“下一个”+
),
助手:函数(){
把手。注册表帮助器(“应答器列表”,功能(上下文,选项){
var输出=”;
$.getJSON('questions',函数(info){
对于(var i=0;i尝试在Handlebar助手中执行AJAX调用不是一件非常有效的事情。助手只知道文本:助手返回一段文本,该文本可能会成为一组DOM节点,但助手无法知道DOM节点是什么,因此当AJAX调用retu时,它无法更新页面上的任何内容从服务器上删除rns
你需要改变你的逻辑:
弄清楚需要进行哪些AJAX调用
执行AJAX调用
当所有AJAX调用完成后,收集模板的数据并将其交给编译后的模板函数
将模板函数的返回值添加到DOM中
在您的情况下,您可以完全摆脱helperOne
。然后,您可能会有一个Answer
主干模型和一个AnswerList
集合,其中包含Answer
s。在某个地方,您可以在AnswerList
上执行获取
,当返回时,您可以更新视图
template: Handlebars.compile(
'<ul>' +
'{{#each models}}<h3>{{attributes.name}}</h3><h4>{{attributes.question}}</h4>'+
'<li>{{#answerList info}} {{{answers}}}{{/answerList}}</li>{{/each}}' +
'</ul>' +
'<button type="button" class="btn btn-danger">Next</button>' +
),
helperOne: function() {
Handlebars.registerHelper('answerList', function(context, options) {
var output = "";
$.getJSON('questions', function(info) {
for (var i = 0; i<info.length; i++ ){
var infos = info[i];
for (key in infos.answers) {
if(infos.answers.hasOwnProperty(key)) {
output += '<li>' +
'">' + info[i].answers[key] +
'</li>';
console.log(output);
}
}
}
});
return output;
}); //end register
},
initialize: function() {
this.listenTo(this.collection, "reset", this.render);
},
render: function () {
this.helperOne();
this.$el.html(this.template(this.collection));
return this;
}