比方說,我的模板看起來像這樣:骨幹 - 獲取從在模板遍歷集合的某型號
<script type="text/template" id="template">
{{#each []}}
<div>{{this.id}}</div>
<div>{{this.name}}</div>
<div>{{this.description}}</div>
<input id="my-btn" type="button">Button</input>
{{/each}}
</script>
模型和集合:
var Item = Backbone.Model.extend({
defaults: {
id: null,
name: '',
description: ''
}
});
var ItemCollection = Backbone.Collection.extend({
model: Item,
url: function() {
return '/items';
}
});
並在視圖我只是取物品和顯示它們:
var ItemsView = Backbone.View.extend({
el: $('#items'),
template: Handlebars.compile($('#template').html()),
items: new ItemCollection(),
initialize: function() {
var self = this;
this.items.fetch({success: function() {
self.render();
}});
},
render: function() {
var items = new ItemCollection();
var html = this.template(items.toJSON());
this.$el.html(html);
}
});
每個項目與它在模板中的字段有它自己的按鈕。
現在我需要添加一個功能,當按下模板中的按鈕時會觸發,所以點擊某個功能必須獲取與模板中的按鈕關聯的項目。
我該怎麼做?
'id'屬性必須是唯一的,或者你沒有有效的HTML。首先解決這個問題,然後花一些時間[精細手冊](http://backbonejs.org/#View-events)。 –
[獲得點擊模型並添加到其他骨幹中的集合]可能的副本(http://stackoverflow.com/questions/9885341/get-clicked-model-and-add-to-other-collection-in-backbone) –