User = Backbone.Model.extend({
urlRoot: "users",
initialize: function(){
this.fetch();
}
});
var HomeView = Backbone.View.extend({
el: '#container',
template: _.template($("#home-template").html(), this.model),
render: function() {
$(this.el).html(this.template);
return this;
}
});
var App = Backbone.Router.extend({
routes: {
'/home': 'home',
},
home: function() {
var user = new User({id: 1});
homeView = new HomeView({
model: user
});
this.homeView.render();
}
});
由于某种原因,我无法将模型数据注入到HomeView的模板中。我看到ajax请求被发送并且返回的数据是正确的。我在调用视图时将静态数据放在同一个地方并且工作正常。
有什么建议吗?
答案 0 :(得分:3)
我认为这是因为您在错误的时间执行模板。它应该在调用render
时完成,如下所示:
var HomeView = Backbone.View.extend({
el: '#container',
template: _.template($("#home-template").html()),
render: function() {
$(this.el).html(this.template(this.model.toJSON()));
return this;
}
});