【发布时间】:2014-02-01 19:59:49
【问题描述】:
我无法从 Underscore 模板运行渲染 HTML。这是代码和错误:
//Code
class QuestionView extends Backbone.View {
template:(data:any) => string = null;
$el = $root;
constructor(options?:any, question?:Question) {
super(options);
this.model = question;
var q = this;
require(["text!add-new-question.html"],
function (html) {
q.template = _.template(html);
}
);
}
render() {
var data = this.model.toJSON();
var html = this.template(data);
this.$el.html(html);
return this;
}
}
class SurveyView extends Backbone.View{
tagName = "div";
template:(data:any) => string = null;
$el = $root;
constructor(options?:any, survey?:Survey){
super(options);
this.template = _.template("<div ><%= enlistQuestions %></div>");
}
enlistQuestions():string{
var questions = "";
_.each(this.collection.models, function(question:Question){
var view = new QuestionView(null,question);
questions += view.template(view.model.toJSON()); // This is line for which the error is shown.
});
return questions;
}
}
//Error
Uncaught TypeError: Property 'template' of object #<QuestionView> is not a function Main.ts:63
(anonymous function) Main.ts:63
j.each.j.forEach underscore.js:79
SurveyView.enlistQuestions Main.ts:61
SurveyView.render Main.ts:69
SurveyView Main.ts:56
(anonymous function) Main.ts:80
【问题讨论】:
-
@muistooshort 谢谢!请查看更新。
-
那是
require调用异步吗?这似乎是QuestionView获得其template属性的地方。您的代码结构很奇怪,通常您会说view.render()而不是像那样乱用view.template,这样您就可以使用DOM 节点和事件。看起来您将所有内容都作为 HTML 字符串处理,因此您已经抛弃了所有视图的 DOM 事件处理,这在 Backbone 应用程序中是一件非常奇怪的事情。 -
@muistooshort 感谢您的更正。
-
@muistooshort。顺便说一句,view() 是用于在屏幕上渲染的。按照惯例,如果您只想返回 HTML 而不是渲染,您会怎么做。
-
不,
view用于渲染到视图的el(即渲染到可能在屏幕上也可能不在屏幕上的 DOM 节点)。如果我想要的只是 HTML,我不会打扰视图,我只会使用模板。问题是 HTML 字符串没有事件,如果你不使用视图的事件,那么你的视图只是一个模板,那么为什么要为所有的视图机制而烦恼呢?如果你不使用视图事件,那么你根本就没有视图,你只是有一个过于复杂的函数来填充模板。
标签: backbone.js underscore.js typescript