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?
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.
But it is a strictly typed programming language. CoffeeScript has high object-oriented capabilities. But it is a dynamic type of programming language.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With