我正在尝试在另一个对象中调用我的视图的“attachmentClicked”函数时进行侦听。这是最初调用该事件的类:
class AttachmentView extends AttachmentViewerView
template: _.template($('#AttachmentViewTemplate').html())
className: "attachmentView"
#
# initialize ->
#
initialize: ->
console.log "AttachmentView initialized"
@render()
events: {
'click' : 'attachmentClicked'
'dblclick' : 'openAttachment'
}
#
# render ->
#
render: ->
@$el.html(@template(@model.toJSON()))
$('div.attachmentViewerView').append(@el)
# @bind 'event', method
#
# attachmentClicked ->
#
attachmentClicked: ->
@$el.addClass('selectedAttachmentView')
此对象在单击时调用attachmentClicked
,现在在另一个创建此对象的类中,我正在尝试侦听该事件。这是那个班级
class AttachmentViewerView extends AttachmentAppController
template: _.template($('#AttachmentViewerTemplate').html())
className: "attachmentViewerView"
#
# initialize ->
#
initialize: (options) ->
console.log "AttachmentViewer initialized"
@office = options.office
@ticket = options.ticket
@attachmentViews = []
@render()
#
# render ->
#
render: ->
@$el.html(@template())
# Append to fileViewer Div
$('#attachmentViewerWindow').append(@el)
@renderFiles()
#
# bindEvents ->
#
bindEvents: (view) ->
@listenTo view, 'attachmentClicked', @attachmentClicked
#
# renderFiles ->
#
renderFiles: ->
@attachments = new AttachmentCollection({@office, @ticket})
@attachments.fetch({
success: (collection) =>
_.each collection.models, (model) =>
# Create the attachment views and bind events right away
@bindEvents new AttachmentView({model: model})
})
#
# attachmentClicked ->
#
attachmentClicked: (attachment) ->
console.log( @ )
@$el.find('.selectedAttachmentView').removeClass('selectedAttachmentView') unless @selected == attachment
@selected = attachment
所以发生的事情是,当创建这个类时,它最终调用renderFiles从服务器获取文件,然后为每个返回的模型创建一个视图,并将其作为参数调用bindEvent。
然后bindEvent尝试侦听新创建的项的attachmentClicked方法,并将其绑定到此类attachmentClicked函数。但是,它不起作用。我尝试了几种方法,但不确定我的问题在哪里。非常感谢指导。
答案 0 :(得分:1)
您正在关注'attachmentClicked'
上的AttachmentView
个活动:
bindEvents: (view) ->
@listenTo view, 'attachmentClicked', @attachmentClicked
但是我没有看到任何会触发这种事件的事情。在如下视图中设置一些DOM事件处理程序:
events:
'click' : 'attachmentClicked'
'dblclick' : 'openAttachment'
仅仅意味着点击会触发attachmentClicked
来电,它不会触发'attachmentClicked'
Backbone事件;如果你想要那个事件那么你必须自己触发它:
attachmentClicked: ->
@$el.addClass('selectedAttachmentView')
@trigger 'attachmentClicked'