small medium large xlarge

Back to: All Forums  CoffeeScript
Profile_pragsmall
08 May 2011, 11:47
Geoffrey Clements (22 posts)

Hi,

Got a copy of the beta book and I’m working my way through it. I think the section on this/@ is good, but I’m a little confused about how ‘this’ relates to ‘$(this)’. You’ll have to excuse me if this is a simple JavaScript question. I know just enough JavaScript to get myself into trouble.

Also, I’m a little confused about accessing the document using $(document). Or am I getting myself caught up in jQuery syntax rather than CoffeeScript?

Finally, the link to the CoffeeScript forum (here) seems to be broken in the pdf.

geoff

Trevor_burnham__goofy_headshot__pragsmall
08 May 2011, 15:39
Trevor Burnham (54 posts)

Hi Geoffrey,

It’s easy to mistake jQuery for magic, but @$@ is just an ordinary function (albeit one with a ton of methods attached). jQuery’s @$@ does different things depending on what kind of argument is passed to it; if you’re in an event callback (e.g. @$(‘li’).click -> $(this)@), then @this@ is a DOM element and @$(this)@ is a jQuery object that “matches” that element. You’ll find that @$(this).length@ is 1 and @$(this)[0]@ is @this@. Likewise, @document@ is a DOM element, so @$(document)@ is a jQuery object that “matches” that element. I should probably add an explanatory sentence in the book about what @document@ is…

A fun way to play with basic jQuery is to go to http://jsconsole.com/ (type @:load coffeescript@ and @:load jquery@ so that you can enter CoffeeScript code and use jQuery); that gives you a REPL where you can test things like @$(document)[0] is document@.

Thanks for letting me know about the broken Discuss link!

You must be logged in to comment