0

我正在将标准 Web 应用程序迁移到主干,今天是第一天,所以假设我犯了一些真正的初学者错误。我有以下 View 类,它需要一个集合。我正在迭代它,它返回它应该基于console.log'ging(注释为'这工作正常')它但它不附加任何东西(注释为'这不起作用')。谁能告诉我这个片段做错了什么?

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);
  }});
4

2 回答 2

0

你能显示你在哪里初始化你的新视图,即:

new HomepagePositionsView({...})

我的猜测是您没有提供要附加的 el,所以发生的情况是您在视图中正确创建了 html,但您没有指定要附加的 DOM 元素。为了清楚起见,它应该看起来像这样:

new HomepagePositionsView({collection: myCollection, el: $('#someElToAttachTo')})

你应该使用 this.$el 而不是 $(this.el),因为 this.$el 是一个缓存的 jQuery 对象。此外,如果您的 Backbone 库是最新的,您可以这样做

this.collection.each(function(){...})

这将委托给 underscore.js,这反过来又会委托给最快的选项,具体取决于浏览器。最后,如果您打算对 Backbone 进行任何认真的工作,我会考虑查看 Marionette.js,因为它为构建大型 js 应用程序提供了许多不错的功能。

于 2013-09-06T04:24:31.040 回答
0

当你遍历你的集合时,this不再引用你的视图对象,你用它来引用你的 el。尝试将其缓存在循环之外,将其分配给 self,然后在从渲染的子视图中附加 el 时从 self 引用您的 el。

var self = this;

this.collection.forEach(function () {
    $(self.el).append(...)
});
于 2013-09-06T05:29:26.877 回答