Reputation: 3
I am trying to set the property of my Backbone view class using a HTML select in Coffeescript and what I've realised is that I need to inject this(@) into the callback/handler via a javascript closure to maintain scope. But I can't seem to figure out how to do this as using "do" just executes the function on page load
dropdown = $('<select />') .on 'change', do(myView = @) -> myVieW.prop = @.value
thanks for your help!
Upvotes: 0
Views: 150
Reputation: 665020
The do
notation does compile to an IIFE, yous still need the actual handler function:
dropdown = $('<select />') .on 'change', do(myView = @) -> (e) -> myVieW.prop = @.value
# or wrap the whole handler assignment:
do(myView = @) ->
dropdown = $('<select />') .on 'change', (e) -> myVieW.prop = @.value
Or you just use lexical this
:
dropdown = $('<select />') .on 'change', (e) => @.prop = e.target.value
dropdown = $('<select />') .on 'change', (e) => @.prop = dropdown.val()
Upvotes: 1
Reputation: 13058
The standard way of doing it in Backbone is the following:
class MyView extends Backbone.View
events:
'change select': 'onChange'
onChange: (e) ->
el = e.currentTarget
@prop = el.value
Having said that, setting some properties on the view is also a smell, and hints on a missing model.
Setting some property outside of the view is a definite smell and invites re-assessment of the architecture.
Upvotes: 1