4 ms·
> Do you have an example of a real-world piece of code that wants to access both the lexical and dynamic "this" Yes. > and isn't a jQuery callback? No :^). A
by mikemaccana 15y ago
> Do you have an example of a real-world piece of code that wants to access both the lexical and dynamic "this"
Yes.
> and isn't a jQuery callback?
No :^). And I wish JQuery ran the callback with a parameter too, so I could access 'this' to refer to the class and use the argument to refer to the object I'm going to run the callback on.
You're totally right that would be neater. Alas Coffeescript is a lot newer than JQuery, so despite technical neatness (or lack thereof in JQuery), Coffeescript has to work with JQuery to grow in popularity.
PS. Thanks for making Coffeescript. It's got me excited about JS again and I absolutely love it.
- jashkenas 15y agoYou'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!