[英]Backbone - Get a certain model from a collection that is iterated in a template
假設我的模板如下所示:
<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);
}
});
模板中帶有字段的每個項目都有其自己的按鈕。
現在,我需要添加一個功能,該功能將在按下模板中的按鈕時觸發,因此在單擊時,某些功能必須獲取與模板中的按鈕相關聯的項目。
我怎樣才能做到這一點?
這是完成要求的一種方法-只需將click處理程序添加到events
哈希( http://backbonejs.org/#View-events )。 我向按鈕添加了數據破折號屬性,以便在單擊處理程序中可以確定要對單擊的按鈕/模型進行操作。
var ItemView = window.Backbone.View.extend({
tagName: 'div',
template: Handlebars.compile($('#template').html()),
events: {
'click .item-btn': 'clickHandler'
},
render: function() {
this.$el.html(this.template({
items: collection.toJSON()
}));
return this; // backbone convention -- return the view
},
clickHandler: function(e) {
alert($(e.target).data().itemId + ' clicked');
}
});
上面的視圖采用以下模板:
<script type="text/template" id="template">
{{#each items}}
<div>{{this.id}}</div>
<div>{{this.name}}</div>
<div>{{this.description}}</div>
<input class="item-btn" data-item-id="{{this.id}}" type="button" value="Button {{this.id}}"></input>
{{/each}}
</script>
這是一個有效的演示: https : //jsfiddle.net/9cgzcc3y/
完成此操作的另一種方法(也是我個人更喜歡的一種方法)是為每個模型創建一個視圖。 這樣,每個視圖將由一個單獨的模型支持。
var ItemView = window.Backbone.View.extend({
tagName: 'div',
template: Handlebars.compile($('#template').html()),
events: {
'click .item-btn': 'clickHandler'
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
},
clickHandler: function() {
alert('clicked: ' + this.model.get('id'));
}
});
var ItemsView = window.Backbone.View.extend({
tagName: 'div',
initialize: function() {
this.collection = collection;
},
render: function() {
var frag = document.createDocumentFragment();
this.collection.each(function(model) {
frag.appendChild(new ItemView({model: model}).render().el);
});
this.$el.append(frag);
return this;
}
});
$('#items').append(new ItemsView().render().$el);
這是該替代方法的工作演示: https : //jsfiddle.net/45kuhp7h/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.