1

我有這樣的代碼:骨幹事件不會把手模板火

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不被解僱。 所有視圖來呈現良好的,但不是工作:( 事件能幫我

回答

1

我認爲你的問題就在這裏:

$('.main').html(this.template({ pages: this.$el.html() })); 

只要你說this.$el.html(),你失去了你的活動。 Backbone將delegate(或其等效on)綁定到視圖的el以進行事件處理,以便將事件處理綁定到DOM節點對象。當您說this.$el.html()時,您已將所有內容都轉換爲字符串,並且該字符串將進入DOM;但事件綁定到DOM元素對象而不是字符串,結果是一切都看起來正確b沒有事件發生。

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); 
+0

是啊,它的工作!謝謝! – Dimich