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" )

出于某种原因,在页面加载时,即使我从未通过在注释视图中按 cmd + b 来发送触发器,也会触发 console.log。任何人都知道为什么 Backbone.Event 会自动触发?

4

1 回答 1

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 --------------------^^^^^^^^^^^^^^^^^^
于 2013-05-31T18:01:56.873 回答