botbot
botbot

Reputation: 7359

Listen to Child Events in Backbone.View

I'd like to listen to an event on a child in my 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

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

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.

Upvotes: 0

Views: 2161

Answers (1)

mu is too short
mu is too short

Reputation: 434635

That's fine, Backbone views have Backbone.Events mixed for a reason.

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; 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.

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. You might want to define update with a fat-arrow (=>) as well:

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

That will give you the right @ (AKA this) when update is called.

Upvotes: 1

Related Questions