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.exten
You could simply add the closure yourself and compile it with the --bare
flag.
coffee -w -c --bare jquery.plugin.coffee
(($) ->
# some code here
)(jQuery)
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.
The easiest way is to extend $.fn object
Simple jQuery plugin can be written in CoffeeScript as follows:
$.extend $.fn,
disable: ->
@each ->
e = $(this)
e.attr("disabled", "disabled") if e.is("button") or e.is("input")
it will compile to
(function() {
$.extend($.fn, {
disable: function() {
return this.each(function() {
var e;
e = $(this);
if (e.is("button") || e.is("input")) {
return e.attr("disabled", "disabled");
}
});
}
});
}).call(this);
UPDATE/EDIT: Yep, as per Jeremy's explanation:
$ = jQuery
$.fn.myPlugin = () ->
console.log('test fired')
compiles to:
(function() {
var $;
$ = jQuery;
$.fn.myPlugin = function() {
return console.log('test fired');
};
}).call(this);
Which works just fine as a jQuery plugin: $('body').myPlugin();
Original:
Okay, i think I may getting close on this one, let me know if it helps.
(($) ->
$.fn.extend =
myplugin: ->
@each: ->
)(jQuery)
renders into:
(function() {
(function($) {
return $.fn.extend = {
myplugin: function() {},
this.each: function() {}
};
})(jQuery);
}).call(this);
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.
You should take a look at the CoffeeScript version of jQuery Boilerplate ~ https://github.com/zenorocha/jquery-boilerplate/blob/master/jquery.boilerplate.coffee