简体   繁体   English

收听Backbone.View中的儿童活动

[英]Listen to Child Events in Backbone.View

I'd like to listen to an event on a child in my Backbone.View. 我想在Backbone.View中听一个孩子的事件。 I thought this would be the correct way to do it but I'm not sure. 我认为这将是正确的方法,但我不确定。 The update function in the parent is not being called. 未调用父级中的更新功能。 Thanks for the help. 谢谢您的帮助。

text.js.coffee text.js.coffee

class App.Views.Text extends Backbone.Views

  initialize: ->
    @_styleToolbar = App.Views.StyleToolbar el: $("#style_toolbar")
    @_styleToolbar.on("update", @update())

  update: ->
    # update text color, font etc

style_toolbar.js.coffee style_toolbar.js.coffee

class App.Views.StyleToolbar extends Backbone.Views
  'change .font_face select' : 'update'

  update: (e) ->
    $(@el).trigger('update', @el)

This is a simplified version of the code, so let me know if there is something missing, I'll update it. 这是代码的简化版本,所以如果有什么遗漏,请告诉我,我将对其进行更新。

That's fine, Backbone views have Backbone.Events mixed for a reason. 很好,Backbone视图中有Backbone.Events混合是有原因的。

You have a couple problems in that code though. 但是,您在该代码中有几个问题。 You need to fix is what is triggering the event, you want to trigger on the view rather than its el ; 你需要解决的是什么触发了事件,要触发的观点,而不是它的el ; this: 这个:

$(@el).trigger('update', @el)

should be: 应该:

@trigger('update', @)

I also switched @el to just @ so that the listener will have access to the whole view object rather than just its el . 我也将@el切换为just @以便侦听器可以访问整个视图对象,而不仅仅是其el

And, the listener should be binding a function rather than the function's return value: 并且,侦听器应绑定一个函数,而不是该函数的返回值:

@_styleToolbar.on("update", @update)

If you use @update() then you'll be calling @update and binding its return value to the "update" event. 如果使用@update()则将调用@update并将其返回值绑定到"update"事件。 You might want to define update with a fat-arrow ( => ) as well: 您可能还需要使用粗箭头( =>定义update

update: (toolbar) =>
  # update text color, font etc

That will give you the right @ (AKA this ) when update is called. 调用update时,它将为您提供正确的@ (又称this )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM