[英]Backbone event doesn't fire with Handlebars template
我有以下代碼:
PageView.js
var PageView = Backbone.View.extend({
events: {
'click .unpublish': 'unpublish'
},
tagName: 'tr',
className: 'pageedit',
template: Handlebars.compile( PageViewTemplate ),
render: function() {
this.$el.html( this.template( this.model ) );
return this;
},
unpublish: function() {
alert('hi');
}
});
PagesView.js
PagesView = Backbone.View.extend({
tagName: 'tbody',
initialize: function() {
this.collection.on('reset', this.render, this);
this.render();
},
template: Handlebars.compile(PagesTemplate),
render: function() {
var countPages = this.collection.at(0).get('count');
_.each(this.collection.at(0).get('pages'), function(model) {
pageView = new PageView({ model: model });
this.$el.append( pageView.render().el );
}, this);
$('.main').html( this.template({ pages: this.$el.html() }) );
this.delegateEvents(this.events);
return this;
},
});
Page.hbs
<td class="pageId">
{{ id }}
</td>
<td class="pagename">
<a href="/pages/{{ alias }}">{{ pagename }}</a>
</td>
<td class="catname">{{ catname }}</td>
<td class="author">{{ author }}</td>
<td>{{ date }}</td>
<td>
{{#if status}}
<a href="#" class="unpublish">
<img src='../{{ siteURL }}assets/img/admin/published.png'>
</a>
{{else}}
<a href="#" class="publish">
<img src='../{{ siteURL }}assets/img/admin/not-published.png'>
</a>
{{/if}}
</td>
<td>
<a href="#" class="intrash">
<img src='../{{ siteURL }}assets/img/admin/delete.png'>
</a>
</td>
Pages.hbs
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Catalog</th>
<th>Author</th>
<th>Date</th>
<th>Status</th>
<th>Intrash</th>
</tr>
</thead>
<tbody>
{{{pages}}}
</tbody>
</table>
在router.js中創建所有實例:
var pages = new Pages();
pages.fetch().done(function() {
new PagesView({ collection: pages});
});
如果我單擊.unpublish鏈接,則不會觸發PageView中的事件。 所有視圖呈現良好,但事件不起作用:(能幫幫我嗎?
我認為您的問題就在這里:
$('.main').html( this.template({ pages: this.$el.html() }) );
一說this.$el.html()
,您就失去了事件。 Backbone將delegate
(或等效的on
)綁定到視圖的el
以進行事件處理,因此事件處理被綁定到DOM節點對象。 當您說this.$el.html()
,您已將所有內容轉換為字符串,並且該字符串進入了DOM; 但事件綁定到DOM元素對象而不是字符串。 結果是一切看起來都很正確,但是沒有事件觸發。
您的Pages.hbs
應該看起來像這樣:
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Catalog</th>
<th>Author</th>
<th>Date</th>
<th>Status</th>
<th>Intrash</th>
</tr>
</thead>
</table>
然后,您應該執行以下操作以獲取頁面上的所有內容:
// Add the basic <table> HTML.
$('.main').html(this.template());
// Append the <tbody> DOM node which has event handling attached to it.
$('.main').find('table.table').append(this.$el);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.