3 ms·
You're in luck then. This is precisely what the fat arrow in CoffeeScript is for: creating a function where the value of "this" is bound lexically. So: cla
by jashkenas 15y ago
You're in luck then. This is precisely what the fat arrow in CoffeeScript is for: creating a function where the value of "this" is bound lexically. So:
class Widget
render: ->
$(".widget-title").click (e) =>
# `this` is still the Widget instance.
# `e.currentTarget` is the DOM element.
- mikemaccana 15y agoI was using the fat arrow, and wanted to keep using it, but switched to thin arrow (using @ to access the element and 'that' to access the class). Here's why: click() works because the callback is given parameter: .click( handler(eventObject) ) Cool. You access @ for the class, and eventObject for the thing you clicked. But I wasn't using click(), I was using load(), which has a different syntax: .load( url, [data,] [complete(responseText, textStatus, XMLHttpRequest)] ) I may be missing something - I only started doing JS seriously last year - but 'complete' doesn't seem to be provided with any parameters, like the element I just loaded. So my only choice, AFAICT, is to use 'this' to access that element. I'd be delighted if that was wrong though. :^) Background: I was trying to get the width of an image file that wasn't in the document, so I could use it to size another image (which happened to use the first image as a webkit mask). Great fun.
- mikemaccana 15y agoCorrecting self: that's the documentation for the wrong .load()! (yes, there's two). The proper docs are http://api.jquery.com/load-event http://api.jquery.com/load-event. Which indeed allows the event to be passed to the callback explicitly, so inside the callback @ refers to the object and 'event' (or whatever) .target refers to the image. Problem solved!