主干并循环访问集合,但结果未追加到 $(this.el)
backbone and iterating through a collection but the results are not being appended to $(this.el)
我正在将标准Web应用程序迁移到主干网,今天是第一天,所以假设我犯了一些真正的初学者错误。我有以下 View 类,它需要一个集合。我正在遍历它,它返回了它应该基于控制台的内容.log'gging(评论为"这工作正常")但它没有附加任何内容(评论为"这不起作用")。谁能通过这个片段看出我做错了什么?
var HomepagePositionsView = Backbone.View.extend({
render:function(){
var str="";
this.collection.forEach(function(location){
var hpsView=new HomepagePositionView({model:location});
//hpView.render();
console.log(hpsView.render().el); // this works ok
//str+=hpView.el;
$(this.el).append(hpsView.render().el); // this doesn't work
});
//$(this.el).text(str);
console.log(this.el); // just <div></div>
return this;
}
});
感谢任何帮助
编辑 #1
这就是我实例化的方式:
homepage_position: function(){
console.log("within homepage_position");
this.homepage_positions= new Locations();
this.homepage_positions.url='/hex-jt/api-homepage-position';
var str="";
this.homepage_positions.fetch({success: function(data){
var hpView= new HomepagePositionsView({ collection:data});
hpView.render();
console.log(hpView.el);
//str+= $.html(hpView.el);
$('#app').html(hpView.el);
}});
当您循环访问集合时,这不再引用您的视图对象,您正在使用该对象来引用您的 el。 尝试将其缓存在循环外部,将其分配给 self,然后在从渲染的子视图中追加 el 时从 self 引用 el。
var self = this;
this.collection.forEach(function () {
$(self.el).append(...)
});
您能否显示在哪里初始化新视图,即:
new HomepagePositionsView({...})
我的猜测是你没有提供一个要附加的el,所以发生的事情是你在视图中正确地创建了html,但你没有指定一个DOM元素来附加到它。为了清楚起见,它应该看起来像这样:
new HomepagePositionsView({collection: myCollection, el: $('#someElToAttachTo')})
你应该使用 this.$el 而不是 $(this.el),因为 this.$el 是一个缓存的 jQuery 对象。此外,如果您的主干库是最新的,您可以这样做
this.collection.each(function(){...})
这将委托给下划线.js,而下划线又会根据浏览器委托给最快的选项。最后,如果你打算用Backbone做任何严肃的工作.js我会考虑看看木偶,因为它需要为构建大型js应用程序提供许多不错的功能。
相关文章:
- 表追加而不附加最后一个元素
- $(this).prop('property') vs. this.property
- Twitter Bootstrap typeahead:使用“this”获取上下文/调用元素
- 在另一个函数中使用变量this
- this.router在AngularJS 2中未定义
- reactjs this.refs vs document.getElementById
- JavaScript 中的嵌套函数和 “this” 关键字
- React+Meteor:this.ops返回未定义
- 如何在jquery中停止在更改时追加值
- javascript中对象构造函数中的var属性与this.properties
- 函数中this和var之间的区别
- jQuery(this).Pparent().Pparente().Prent().find()在iPad上不起作用
- JQuery.on(“keydown”)追加到页面时不工作
- Understanding Javascript scope with "var that = this&qu
- 定义this.properties或objectName.properties的javascript JSON对象
- Object.prototype using 'this'
- 在JavaScript类型的函数中避免self-this
- 如何使用(this)访问Angular 2 http rxjs catch函数中的对象属性
- jQuery[button.class]未检测到用按钮追加行
- 主干并循环访问集合,但结果未追加到 $(this.el)