我正在尝试在questionListView中使用render函数,它似乎正在运行,但是没有更新页面。
模板:
<script id="myTemplate" type="text/template">
<p>Test</p>
</script>
JS的一部分:
$(function(){
//Test data
var initialListData = [
{ listName: "Sample Questions", listID: 1},
{ listName: "Default questions", listID: 2}
];
// MODELS ----------------------------------------------------
var questionList = Backbone.Model.extend({
defaults: {
listName: "Name of the list",
listID: 0
}
});
// COLLECTIONS ----------------------------------------------------
var populateList = Backbone.Collection.extend({
model: questionList
});
// VIEWS ----------------------------------------------------
var questionListView = Backbone.View.extend({
template: $("#myTemplate").html(),
render: function () {
console.log('I can see this, but nothing happens...');
var tmpl = _.template(this.template);
$(this.el).append(tmpl(this.model.toJSON()));
return this;
}
});
var AppView = Backbone.View.extend({
el : $("#content"),
initialize: function (){
this.collection=new populateList(initialListData);
this.render();
},
render: function (){
_.each(this.collection.models, function (item) {
this.renderSelect(item);
}, this);
},
renderSelect: function(item){
var populateQuestionList = new questionListView({
model: item
});
this.$el.append(populateQuestionList.render().el);
}
});
var app = new AppView();
} (jQuery));
谢谢!
答案 0 :(得分:3)
你是否在回调document.ready事件时触发了这个?如果没有,您的代码可能在DOM实际加载并准备好之前执行。尝试:
$(function () {
var app = new AppView();
});
一些错误点。
template: _.template($("#myTemplate").html())
将模板功能缓存为微优化this.$el
代替$(this.el)
。你已经在一个地方做了这个,但不是两个都这样做。