2013-03-10 101 views
1

我只是在Backbone身上弄溼了自己的腳,並且我認爲我有一個很容易解決的問題。我有以下看法這是一個簡單的標籤,當點擊打開了一個面板和關閉時可以追溯到一個標籤:除了「closePanel」被多次調用的骨幹事件

myApp.views.Support = { 
    Form: Backbone.View.extend({ 
     initialize: function() { 
      this.el = $('#support'); 
      this._ensureElement(); 
     }, 
     render: function() { 
      if (this.$el.hasClass('support-panel')) { 
       // close panel 
       this.$el.empty(); 
       this.$el.removeClass('support-panel'); 
       this.$el.addClass('support-button'); 
      } 
      else { 
       // open and populate panel 
       var template = _.template(myApp.utils.RenderTemplate('support/default'), {}); 
       this.$el.removeClass('support-button'); 
       this.$el.addClass('support-panel'); 
       this.$el.html(template); 
      } 

      return this; 
     }, 
     closePanel: function() { 
      alert('close event fired'); 
     }, 
     events: { 
      'click #SubmitFormButton': 'submitForm', 
      'click #CloseSupportPanel': 'closePanel' 
     }, 
     submitForm: function (event) { 
      alert('form submitted: ' + $('#message')); 
     } 
    }) 
} 

一切正常+2次每次被炒魷魚點擊事件發生。我認爲這是我失蹤的某種清理,但我不知道是什麼。

回答

3

可能是因爲事件正在冒泡。嘗試返回false

+0

這工作,但似乎不是「最好」的方式來做到這一點。我完全承認,我絕對沒有這種說法的基礎,也許這是處理這種情況的正確方法。你怎麼看? – Matt 2013-03-11 00:52:15

+0

它是正確的做法。這就是JavaScript的工作方式。 – 2013-03-11 01:13:08

1

我知道這是一個老問題,但它幫助我意識到我的問題是什麼。如Daniel說的那樣返回錯誤,但我的問題的根本原因是在我的標記中有兩次jQuery選擇器,導致創建兩個jQuery對象,因此click事件觸發兩次。

+0

感謝您指點我正確的方向! – Tuan 2015-07-27 07:42:01