Writing a jQuery plugin with coffeescript


Posted on 12th April, by Tobias.Braner in Ruby, Sonstiges. 1 Comment

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







MacRuby – Create iCal event with alarm from Ruby
I've had to create some very similar events in my calendar, but they did not match a valid recurrence pattern. As I find it...
Windows: Get the mouse position with Ruby
With this Ruby code you can get the mouse position in windows.
lol-patch.com
I guess not everyone reading this article is a fan of League of Legends (LoL), a famous multiplayer game in which two enemy factions...
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...
Uninstall all local ruby gems
This ruby script might be useful for people like me who just started using bundler to manage the gems of their webapp and all...
Installing GIT on Mac with Macports

This small guide will help to install GIT on Mac using Macports.

Rake & FTP
Rake is a build tool for ruby, similar to C's make or Java's ant/maven. Basically you can define a lot of tasks, which can be...
Ruby web scraping
I want to share my recent experience with ruby web scraping and RSS. Often I found myself checking the comments for my game iBox3D...
iBox3D released
Back in 2009, on the 23rd of March, I've reported about an easy way to created 3D iPhone games with Shiva, a game creation...