Reputation: 3653
I'm building an app using Backbone.js however I have run into a problem that I can't fix very early on.
I have a simple list / detail view setup right now but everytime I render the detail view my events are compounded. Eg show two detail views and clicking a link will cause it to be clicked twice.
My view looks like this (written in CoffeeScript):
#
# Project List View
#
class ProjectListView extends Backbone.View
el: $("#projectList")
events : {
"click #addProject" : "createNewProject"
}
initialize : ->
@template = _.template(app.projectListView)
_.bindAll(this, "render", "createNewProject")
@render()
createNewProject : (e) ->
e.preventDefault()
e.stopPropagation()
tempProject = Projects.create({
title : 'Test Project'
description : ''
browserDefault : 12
lineHeight : 21
})
render : =>
$(@el).html(@template())
@delegateEvents()
return @
Obviously take the events has out and I don't get any clicks events firing. What am I missing here?
Upvotes: 3
Views: 3302
Reputation: 77416
The code you pasted in doesn't appear to be indented properly. Is that how it was originally?
You don't need the _.bindAll
line. Instead, just use =>
to define your methods (instead of ->
)
I made some stylistic changes and took out the extra @delegateEvents
, as Julien suggested. See if this works:
class ProjectListView extends Backbone.View
el: $("#projectList")
events:
"click #addProject" : "createNewProject"
initialize: =>
@template = _.template(app.projectListView)
@render()
createNewProject: (e) =>
e.preventDefault()
e.stopPropagation()
tempProject = Projects.create
title: 'Test Project'
description: ''
browserDefault: 12
lineHeight: 21
render: =>
@el.html @template()
@
Upvotes: 3
Reputation: 9216
Here are my comments on your code. Backbone will automatically delegate the events (using delegateEvents) based on your events option. You do not have to do it in the render function (most probably the cause of double events thrown at you). Remove deleteEvents from your render.
Also, @el is already defined as a jQuery object, so you do not have to do it again within your render.
Will you be creating 2 project list views? If so ids must be unique...
Upvotes: 2