2014-02-22 63 views
1

渲染我的播放器時遇到了一些問題。 我試着去創建一個使用backbonejs的結構,將更新集合中的視圖

  • 添加一個新的播放器視圖當一個新的玩家加入
  • 更新球員得分

updatePlayerData我更新的球員得分,如果球員模型已經創建。如果沒有,我創建一個新的。

問題出在playerScore。我每次創建一個跨度render被調用。這導致許多playerclasses被創建在一個玩家視圖下

我需要能夠遍歷我當前的視圖並更新某個id的玩家。我需要再渲染該播放器視圖,以便顯示新內容。

僅供參考,這裏是我到目前爲止的代碼:

var Player = Backbone.Model.extend({}); 

var PlayerView = Backbone.View.extend({ 
    className: 'player', 
    initialize: function() { 
     _.bindAll(this, 'render'); 

    }, 
    render: function() { 
     this.playerScore(); 
     return this; 
    }, 
    playerScore: function(){ 
     $('<span/>', { 
      class: 'playerScore' 
     }).appendTo($(this.el)).html(this.model.get('score')); 

    } 
}); 

var Team = Backbone.Collection.extend({ 
    model: Player 
}); 

var TeamView = Backbone.View.extend({ 
    el: '#users', 
    initialize: function() { 
     _.bindAll(this, 'updatePlayerData', 'addPlayer'); 
     this.collection.bind('add', this.addPlayer); 
     this._subviews = []; 
    }, 
    updatePlayerData: function (playerEntity) { 
     var view = _(this._subviews).find(function(v){ 
       return playerEntity.id == v.model.get('id'); 
     }); 
     if(view){ 
      view.model.set({ 
       score: playerEntity.score 
      }); 
      view.render(); 
      return; 
     } 
     var playerModel = new Player(); 
     playerModel.set({ 
      score: playerEntity.score 
     }); 
     this.collection.add(playerModel); 
    }, 
    addPlayer: function (player) { 
     var playerView = new PlayerView({ 
      model: player 
     }); 
     var playerHtml = playerView.render().el; 
     $(this.el).html(playerHtml); 
     this._subviews.push(playerView); 
    } 
}); 

回答

1

嘗試修改您的playerScore方法是這樣的:

playerScore: function() { 
    if (!$(this.el).find('span.playerScore').length) { 
     $('<span/>', { 
      class: 'playerScore' 
     }).appendTo($(this.el)).html(this.model.get('score')); 
    } else { 
     $(this.el).find('span.playerScore').html(this.model.get('score')); 
    } 
}