Reputation: 502
I've been struggling through my first Backbone app and have started to get the hang of things. I now have a few successful reports that load JSON data from my server (NodeJS), populate a template (Handlebars), and render relatively nicely on the frontend.
The issue I'm running into is that I'm trying to add event handlers to a <select>
object coming in from one of my templates and I'm not having much luck.
Here's the template:
// Report - New Clients
script(type='text/x-handlebars-template', id='newClients-template')
// Start Listing
{{#each report}}
.listingName
.youSearched
| Stylist:
.srchResult
select.chzn-select(id='stylists', style='width:350px')
option(value='null') All Stylists
{{#each stylists}}
option(value='{{uid}}') {{name}}
{{/each}}
.clear
And here's the Backbone View:
note: I'm calling the view from within a $ ->
so it shouldn't be loading until DocumentReady
# View
class window.NewClientsView extends Backbone.View
events:
'click #stylists': 'selectStylist'
initialize: ->
@el = $('.containerOuter')
_.bindAll this, 'render'
@collection.bind 'reset', @render
# Compile Handlebars template at init (Not sure if we have to do this each time or not)
source = $('#newClients-template').html()
@template = Handlebars.compile source
# Get the latest collections
@collection.fetch()
render: ->
# Render Handlebars template
renderedContent = @template { report: @collection.toJSON() }
$(@el).html renderedContent
return this
selectStylist: (e) ->
console.log 'hit it!'
console.log e
I'm expecting that any time the dropdown is clicked or changed, I'll see the selectStylist
function fired. Unfortunately that hasn't happened yet :( I also have inspected the element in Chrome Dev Tools and there are no event listeners set on the object.
I've been stuck on this for a bunch of hours now and have reviewed all the other suggestions for Backbone event listeners (i.e. pass in your this.el
as a parameter when instantiating your view), but haven't had any success.
Any help or ideas would be appreciated!
Upvotes: 1
Views: 2972
Reputation: 77426
In initialize
, you write
@el = $('.containerOuter')
But Backbone.js processes events
before initialize
—meaning that it's already bound those events to a different @el
(which you should see in the DOM as a lonely div
).
You can hack this by overriding make
, the function that's used to create @el
:
make: ->
$('.containerOuter')[0]
Upvotes: 1