I recently started playing with Backbone and CoffeeScript using Brunch and was wondering why something like this...
events: {
"click .button" : "open",
"hover .info" : "hover"
},
hover: =>
$(this).css("background-color", "#333")
..does not work.
From my understanding CoffeeScript has its own version of this
which could conflict with what jQuery uses but in the documentation I thought =>
binds it to the current object. I have also tried ->
as well to no avail. Any idea on why this doesn't work?
HTML:
<div id='outer'>
<div class='.info'> <a href='google.com'> google </a> </div>
<div class='.info'> <a href='google.com'> google </a> </div>
<div class='.info'> <a href='google.com'> google </a> </div>
</div>
From the docs:
All attached callbacks are bound to the view before being handed off to jQuery, so when the callbacks are invoked,
this
continues to refer to the view object.
And if this
is the view object (rather than, say, an HTML element), $(this)
is fairly meaningless. What you want to do, I believe, is pass the element to which the view refers to $
, e.g.:
hover: =>
$(this.el).css("background-color", "#333")
# -----^
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With