0

This ticket doesn't help, and the samples there do not work for me. I can't quite seem to get jQuery's delegate to work properly.

Here is the JSFiddle which does not dynamically declare events correctly. How do I do this?

What's happening in the fiddle?

The override for dynamic events:

Backbone.View::addEvents = (events) ->
  @delegateEvents _.extend(_.clone(@events), events)  

A class to aggregate the DOM selectors/events, so we only declare their HTML counterparts once:

class Els
  constructor: () ->
    @signupButton = 'button#signup'
  events: () ->
    events = { }
    events['click ' + @signupButton] =  'clickSignup'
    events

A class to handle DOM manipulation:

class UI extends Backbone.Model
  disableButton: () ->
    $(els.signupButton).addClass('disabled') 

Marionette views:

class MyRegion extends Backbone.Marionette.Region
  el: '#default-region'

class MyLayout extends Backbone.Marionette.Layout
  template: '#template-layout'
  regions:
    content: '#region-content'
  #events:
    #'click button#signup': 'clickSignup'
  initialize: (options) ->
    # This seems correct
    alert JSON.stringify(options.dynamicEvents)
    # FAIL!
    @addEvents options.dynamicEvents
  close: () ->
    @remove()
    @unbind()  
  clickSignup: (event) ->
    ui.disableButton()

App start:

els = new Els()
ui = new UI()

app = new Backbone.Marionette.Application()
app.start { }   

region = new MyRegion()

region.show new MyLayout(
  dynamicEvents: els.events()
)

It would be cool if I could also declare the event bindings within Els, e.g.:

class Els
  constructor: () ->
    @signupButton = 'button#signup'
  events: () ->
    events = { }
    events['click ' + @signupButton] =  (event) ->
      ui.disableButton()
    events

I really should use the EventEmitter, but the examples assume everything is instantiated.

Community
  • 1
  • 1

1 Answers1

0

This works as expected

Backbone.View::addEvents = (events) ->
  @events = _.extend @events or {}, events
  @delegateEvents()
rdiazv
  • 1,153
  • 7
  • 7
  • That can inadvertently modify the class's `events` rather than just the instance's (http://jsfiddle.net/ambiguous/xBnGA/). You might want to `@events = _({}).extend(@events, events)` instead. – mu is too short Dec 04 '12 at 20:15