2013-10-18 72 views
-1

我有一个骨干模板来表示足球运动员列表。渲染完成后,我通过向其中插入其他模板来修改一些模板元素。视图渲染()函数是:无法从Backbone模板获取元素

render: function() { 
     that = this; 
     this.$el.html(template(this.model.attributes)); 

     var homeTeam = new player.PlayerCollection({team_id: this.model.get('home_id')}); 

     homeTeam.fetch({ 
     data: { forward_first:true, exlude_keepers:true}, 
     processData: true, 
     success:function (collection) { 

      var forwards = collection.where({'position':'Forward'}); 
      new PlayerListGoalView({players: forwards, 
            position:"Forward", 
            el: $("#home-forwards", that.el), 
            player_id:that.player_id 
           }); 


      } 
     }); 


     this.prepareList(); 
    }, 

生成的HTML有一系列的嵌套列表,例如:

<ul id="expList" class="topcoat-list list"> 
    <li id="home-forwards"> 
     <ul class="topcoat-list list"> 

      <li class="topcoat-list__item " id="player-713"> 
       <span>Fabio Borini</span>  
      </li> 

      <li class="topcoat-list__item " id="player-696">   
       <span>Jozy Altidore</span> 
      </li> 

      <li class="topcoat-list__item " id="player-697"> 
       <span>Mikael Mandron</span>  
      </li> 

     </ul> 
    </li> 
    <li id="away-forwards"> 

    </li> 
    <li id="home-midfielders"> 

    </li> 
    <li id="away-midfielders"> 

    </li> 
    <li id="home-defenders"> 

    </li> 
    <li id="away-defenders"> 

    </li>  
    </ul> 

中prepareList(),我得到的主UL,然后它的li孩子有自己的ul:

prepareList: function(){ 

     var ul = this.$('#expList'); 
     var el = ul.find('li:has(ul)'); 

     console.log('ul.length is:'); 
     console.log(ul.length); 
     console.log('el.length is:'); 
     console.log(el.length); 

    }, 

这导致“ul.length is:1”和“el.length is:0”。所以它得到了ul,但不是li。

当我在chrome检查器中展开ul标记时,可以看到firstElementChild是li#home-forward,并且所有innerHTML都如上所示。但它仍然无法得到李。

现在,如果我将上面的HTML硬编码到模板中,则会找到ul和li!

任何想法?

+0

这是什么:'$(“#home-forwards”,that.el)'for?不应该是'el:那。$(selector)'?或者可能'el:$(“#home-forwards”)' –

回答

0

你应该在你的“成功”回调中调用this.prepareList()。 现在你可以在集合尚未成功获取时调用它。

+0

@ user1716672试试这个...... – user10