kidcapital
kidcapital

Reputation: 5174

Why wont' backbone fire my event?

My class is defined as below:

class NewUser extends Backbone.View
  template : JST["backbone/templates/events/new"]
  events : 
    'click button' : 'hello'
  hello : ->
    alert('hi')
  render : ->
    @el = $(@template())
    @ 

I initialize the page as follows:

$('body').append(new NewUser().render().el)

Yet when I click the button, no alert displays. Does anyone see anything wrong with my code? The view renders, but the events never register.

Upvotes: 0

Views: 438

Answers (2)

mu is too short
mu is too short

Reputation: 434665

You're creating your @el in your render method:

render : ->
    @el = $(@template())
    @ 

but you neglect to call delegateEvents:

Uses jQuery's delegate function to provide declarative callbacks for DOM events within a view. [...] By default, delegateEvents is called within the View's constructor for you [...]

So, your events never get bound to the @el that you add to the DOM and your button does nothing useful. Your render should look like this:

render : ->
    @el = $(@template())
    @delegateEvents()
    @

Upvotes: 1

Paul
Paul

Reputation: 18597

Is the button part of the template which is rendered to the view's el?

If it's not then the hello event won't be fired because the events hash is limited to events within the view itself. You will need to manually bind to the event in the render method in that case

render : ->
  @el = $(@template());
  $('#buttonId').click(@hello);

Upvotes: 0

Related Questions