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.
class Widget
render: ->
$(".widget-title").click (e) =>
# `this` is still the Widget instance.
# `e.currentTarget` is the DOM element.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.
AccountView.prototype.render = function() {
$(".account").click(function(e) {
// `this` is now the same as `e.currentTarget`
// But `e.target` is also useful.
// And you what you really want is for `this`
// to still point at the AccountView instance.
});
}; AccountView.prototype.render = function() {
$(".account").click( { that: this }, function(e) {
// 'that' now holds a reference to AccountView
});
};
If you don't want to use (or you are using an older version of jquery without the eventData) you could use a closure: $(".account").click( (function(that) {
return function(e) {
// 'that' now holds a reference to AccountView
})(this);
});You realize you're replying to the author of CoffeeScript?