2015-06-21 56 views
1
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? 
    } 

}); 

enter image description here刪除收集單一模式在Backbone.View

嘿,我拿什麼報答玩家的整個集合,它看起來像名單和[編輯]按鈕,他們每個人。當我點擊編輯按鈕時,如何從我的精確播放器集合中獲取模型,該按鈕位於旁邊?有一個簡單的方法,或者我必須讓父母字段「值」包含其ID,然後在我的收藏中查找此ID?

回答

0

您必須在集合中搜索模型的ID。

請注意,骨幹網將傳遞給您的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")) 
    } 

}); 
+0

非常感謝。我做了另一種方式:this.collection.get($(e.target).parent()。attr(「value」));我從父母那裏得到身份證。 – Humberd