0

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.

botbot
  • 7,299
  • 14
  • 58
  • 96

1 Answers1

1

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.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • thanks mu, i will try that now. would you recommend doing things this way? or should these just ignore each other and communicate through the model / collection updates (since these changes are stored in the db)? I often see solutions posted that say suggest just making the child part of the parent, but that doesn't seem very dry or OOP to me. – botbot Jul 23 '12 at 23:52
  • 1
    @masterkrang: Depends (as usual). If you want to make the settings persistent then a separate settings model that `Text` would listen to (for `"change"` events) and `StyleToolBar` would call `set` on would make sense. If you don't want persistence then a simple `Backbone.Events` instance could be used as a simple pub-sub object. For something simple, having views talking to each other through events is reasonable but be prepared to switch to one of the other approaches when things get more complicated. – mu is too short Jul 24 '12 at 00:00
  • implemented this and seems to be working, thanks again. will come back for more later when "things get more complicated". :) – botbot Jul 24 '12 at 00:09