I've shown how to write a jQuery plugin in CoffeeScript in a previous post. In the following example, I take that simple jQuery plugin and add a little more sugar.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
do ($) -> | |
methods = | |
init: (options) -> | |
options = $.extend dialogSelector:'.dialog', inputSelector:'.input', options | |
dialogElement = $(options.dialogSelector) | |
dialog = dialogElement.dialog autoOpen: false, modal: true, resizable: false | |
$(options.inputSelector).click -> dialog.dialog 'open' | |
$.fn.simple = (method) -> | |
[_, args...] = arguments | |
if methods[method] then methods[method] args... | |
else if typeof method is 'object' or not method | |
methods.init arguments... | |
else $.error("Method #{method} does not exist in jQuery simple") |
Line 10 (i.e. [_, args...] = arguments) is using two cool CoffeeScript features. The first is something called destructuring assignment. This feature allows you to take data from arrays or objects and place that data into something more wieldy. In this case, we are taking the JavaScript arguments object, destructuring it, and assigning all of the arguments except the first one to an array named args. This eliminates the need for me to type Array.prototype.slice.call(arguments, 1). If I had not used a splat (i.e ...), this would have assigned only the second argument to args. Note: Destructuring assignment has been added to JavaScript 1.7.
The second thing of interest on this line (which I've already briefly mentioned) is the use of the splat. The splat allows you to easily work with anything that involves a variable number of arguments. Since line 10 potentially involves more than 2 passed arguments, this is a perfect place to use a splat. As I mentioned before, the use of the splat in this case will generate JavaScript to slice the arguments array i.e. Array.prototype.slice.call(arguments, 1).
Lines 11 and 13 also use a splat, but the reasoning behind its use on these lines is slightly different. While this is still related to a varying number of arguments, it has to do with the passing of those arguments to a function rather than retrieval of the additional argument values. The splat in this case will generate JavaScript that uses the Function.apply method.
A little bit of sugar can make things much sweeter (ug...that was bad). I hope you find this post helpful and that you find lots of uses for the described features.