Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a jquery plugin in coffeescript - how to get "(function($)" and "(jQuery)"?

I am writing a jquery plugin in coffeescript but am not sure how to get the function wrapper part right.

My coffeescript starts with this:

$.fn.extend({     myplugin: ->         @each -> 

Which creates the javascript with a function wrapper:

(function() {   $.fn.extend({       myplugin: function() {           return this.each(function() { 

but I want a '$' passed in like this:

(function($) {   $.fn.extend({ 

Similar for the ending I have... nothing in particular in coffeescript.
I get this in javascript:

})(); 

But would like this:

})(jQuery); 

Does anyone know how to achieve this with the coffeescript compiler? Or what is the best way to get this done within coffeescript?

like image 635
PandaWood Avatar asked Dec 26 '10 12:12

PandaWood


People also ask

How do you write a function in CoffeeScript?

To define a function here, we have to use a thin arrow (->). Behind the scenes, the CoffeeScript compiler converts the arrow in to the function definition in JavaScript as shown below. (function() {}); It is not mandatory to use the return keyword in CoffeeScript.

Is CoffeeScript typed?

But it is a strictly typed programming language. CoffeeScript has high object-oriented capabilities. But it is a dynamic type of programming language.


2 Answers

The answer is that you don't need to call it like that in CoffeeScript -- your script is already safely wrapped in a closure, so there's no need for jQuery-passed-in-as-a-parameter-tricks. Just write:

$ = jQuery 

... at the top of your script, and you're good to go.

like image 60
jashkenas Avatar answered Sep 22 '22 00:09

jashkenas


Unless you're using the --bare flag in the compiler, the

$ = jQuery 

solution is best. If you are, then with the new do keyword, you can write

do ($ = jQuery) ->    # plugin code... 

thus creating the desired scope while avoiding a mess o' parentheses.

like image 35
Trevor Burnham Avatar answered Sep 24 '22 00:09

Trevor Burnham