Javascript 主干错误中的渲染
我正在尝试渲染,但我不完全了解javascript并比较此错误: 未捕获引用错误:未定义包装。 我将在同一视图中呈现集合获取的结果Javascript 主干错误中的渲染,javascript,backbone.js,handlebars.js,Javascript,Backbone.js,Handlebars.js,我正在尝试渲染,但我不完全了解javascript并比较此错误: 未捕获引用错误:未定义包装。 我将在同一视图中呈现集合获取的结果 var HomeView = Backbone.View.extend({ template: Handlebars.compile(template), events: { }, initialize: function() { console.log("inhomeview"); var amici =
var HomeView = Backbone.View.extend({
template: Handlebars.compile(template),
events: {
},
initialize: function() {
console.log("inhomeview");
var amici = new Usercollection();
amici.fetch({
success: function() {
amici.each(function(object) {
console.log(object.toJSON());
var wrapper=object.toJSON();
});
},
error: function(amici, error) {
// The collection could not be retrieved.
}
});
this.render();
},
render: function() {
var context=wrapper;
var html =this.template(context);
this.$el.html(html);
return this;
}
});
return HomeView;
});
也许您希望执行类似的操作(请阅读下面代码中的注释):
您正在一个完全不同的函数中定义
包装
变量,因此它在呈现
的作用域中不可用。现在我已将包装定义为全局作用域,但比较此错误:未捕获类型错误:无法读取未定义的属性“object”
var HomeView = Backbone.View.extend({
template: Handlebars.compile(template),
initialize: function() {
// its better to pass collection into view and listen to its 'reset' event
this.collection.on('reset', this.render, this)
},
render: function() {
// convert collection to json and pass to template as "users"
var html = this.template({users: this.collection.toJSON()});
this.$el.html(html);
return this;
}
});
// This is how you should be using it later in your code:
// create collection and pass it in home view
var users = new Usercollection(),
homeView = new HomeView({collection: users,
el: '#pagina'});
// fetch collection, this will trigger 'reset' event
// so your view will render itself
users.fetch();