Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery $(this) not working in coffee script / backbone

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>
like image 274
coffeetime Avatar asked Dec 04 '22 06:12

coffeetime


1 Answers

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")
  # -----^
like image 139
Jordan Running Avatar answered Dec 18 '22 06:12

Jordan Running