2013-05-31 221 views
0

所以我有一個奇怪的問題,即使他們還沒有被觸發,我的骨幹事件也被解僱了。基本上我正在做一個音符編輯器應用程序。在筆記本身中,用戶可以按cmd + b加粗文本或任何其他法線。然後觸發一個事件,該事件冒泡到應該訂閱該事件的AppController並調用正確的方法。骨幹事件被觸發而沒有觸發器

這裏是筆記的圖,其中觸發器被稱爲:

class MeetingNote.View.NoteView extends Backbone.View 
    adminTemplate: _.template($('#AdminNoteTemplate').html()) 
    normalTemplate: _.template($('#NormalNoteTemplate').html()) 
    className: 'note' 
    events: 
      'keydown'      : 'handleKeyDownsForStyling' 

    # all of the normal backbone stuff.... init/render/blah 

    handleKeyDownsForStyling: (e) -> 
      if @admin == true 
         if e.metaKey 
          switch e.which 
            when 66 then @trigger "boldSelection" 
            when 73 then @trigger "italicizeSelection" 
            when 85 then @trigger "underlineSelection" 

然後,這裏是我的AppController其中,當NoteView被實例化

class MeetingNote.View.AppController extends Backbone.View 
    template: _.template($('#MeetingNoteAppTemplate').html()) 
    className: 'MeetingNoteApp' 
    initialize: (options) -> 
      @admin = options.privilege             
      @render() 
    render: -> 
      @$el.html(@template()) 
      $('#container').append(@$el) 
      @initializeApp() 

    initializeApp: ->          
      @adminTools = new MeetingNote.View.AdminTools if @admin == true 
      notes = new MeetingNote.Collection.NotesCollection() 
      notes.fetch { 
        success: (collection) => 
          _.each collection.models, (model) => 
            note = new MeetingNote.View.NoteView {model: model, privilege: @admin} 
            @bindNoteEvents note if @admin == true 
      } 

    bindNoteEvents: (note) -> 
      note.on "boldSelection", @adminTools.boldSelection(), note 
      note.on "italicizeSelection", @adminTools.italicizeSelection(), note 
      note.on "underlineSelection", @adminTools.underlineSelection(), note 

最後結合該事件,這裏是@ adminTools.boldSelection()函數

boldSelection: -> 
      console.log("yo") 

出於某種原因,在頁面加載時,該console.log被解僱,即使我從來沒有通過在note View中按cmd + b發送觸發器。任何人都知道爲什麼Backbone.Event會自動啓動?

回答

2

這是一個函數調用:

@adminTools.boldSelection() 
#------------------------^^ 

這是一個函數的引用:

@adminTools.boldSelection 

你應該用手on對函數的引用,以便它可以調用功能稍後。你的bindNoteEvents應該看起來更像這樣:

bindNoteEvents: (note) -> 
     note.on "boldSelection",  @adminTools.boldSelection,  note 
     note.on "italicizeSelection", @adminTools.italicizeSelection, note 
     note.on "underlineSelection", @adminTools.underlineSelection, note 
     # No parentheses here --------------------^^^^^^^^^^^^^^^^^^ 
+0

你是搖滾樂隊的傢伙。謝謝。 –