我在渲染播放器时遇到了一些麻烦。 我试图使用
的backbonejs创建一个结构在updatePlayerData
中,如果已经创建了玩家模型,我会更新玩家得分。如果没有,我会创建一个新的。
问题出在playerScore
。我每次调用render
时都会创建一个跨度。这导致许多player
classes
在一个玩家视图下创建
我需要能够遍历当前视图并更新某个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);
}
});
答案 0 :(得分: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'));
}
}