Writing a jQuery plugin with coffeescript
Coffescript saves my day, as I don’t like javascript and the coffeescript syntax is more python/ruby based. Coffeescript itself compiles to javascript. It is very easy to learn, nevertheless it was not easy to create the basic code to register a new jQuery plugin. The following code serves as template:
1 2 3 4 5 6 7 8 9 10 11 | $ = jQuery methods = init: (options) -> obj = @ # do something $.fn.your_plugin_name = (method) -> if method of methods return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ) ); else $.error( "Method #{method} does not exist on jQuery.your_plugin_name" ); |
This coffeescript compiles to:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | var $, methods; $ = jQuery; methods = { init: function(options) { var obj; return obj = this; } }; $.fn.your_plugin_name = function(method) { if (method in methods) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else { return $.error("Method " + method + " does not exist on jQuery.your_plugin_name"); } }; |
You would call your plugin e.g. this way (from javascript):
$('#target_div').your_plugin_name('init', {your: "option"});
If you are still waiting for the *Yeah, I have to use coffeescript!”-moment read this:
The lines of code of my jQuery plugin were reduced by 50% and the code is much more readable now! Don’t miss the coffeescript page which will give you much more arguments for coffeescript as I could ever do here.
Comments
Powered by Facebook Comments