var PlayersView = Backbone.View.extend({
collection: players, //collection of players
el: "#playersList", //I bind to the class
render: function () {
this.$el.html("");
for (var i=0; i<this.collection.size(); i++) {
var player = this.collection.at(i);
this.$el.append("<li "+"value='"+player.get("id")+"'>"+player.get("names")[0]+" "+player.get("surnames")[0]+" <a href='#' class='edit'>[edit]</a>"+"</li>");
} //what I render is in the picture below
return this;
},
events: {
'click .edit': 'edit',
},
edit: function () {
console.log(???); //what to write?
}
});
嘿,我渲染了一整套玩家,它们看起来像名单和[编辑]按钮。当我单击编辑按钮时,如何从我的确切播放器集合中获取模型,该按钮位于旁边?是否有一个简单的方法或我必须得到父母的领域&#34;价值&#34;包含其ID,然后在我的集合中查找此ID?
答案 0 :(得分:0)
您必须在集合中搜索模型的ID。
请注意,backbone将作为表示click事件的对象的第一个参数传递给edit
函数。 click事件的target
属性将是单击的元素。您可以最简单地为编辑链接指定与您的模型ID匹配的id属性。
var PlayersView = Backbone.View.extend({
collection: players, //collection of players
el: "#playersList", //I bind to the class
render: function () {
this.$el.html("");
for (var i=0; i<this.collection.size(); i++) {
var player = this.collection.at(i);
this.$el.append("<li "+"value='"+player.get("id")+"'>"+player.get("names")[0]+" "+player.get("surnames")[0]+" <a href='#' id='" + player.get("id") + "' class='edit'>[edit]</a>"+"</li>");
} //what I render is in the picture below
return this;
},
events: {
'click .edit': 'edit',
},
edit: function (e) {
this.collection.get(e.target.get("id"))
}
});