无触发器触发的骨干事件

时间:2013-05-31 17:24:10

标签: coffeescript backbone-events

所以我有一个奇怪的问题,我的骨干事件即使尚未被触发也会被解雇。基本上我正在做一个笔记编辑器应用程序。在注释本身中,用户可以将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会自动触发?

1 个答案:

答案 0 :(得分: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 --------------------^^^^^^^^^^^^^^^^^^