2013-05-31 71 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

你是摇滚乐队的家伙。谢谢。 –