I have never been one to write extension methods in jQuery, I suppose that’s because I have not written anything that hasn’t already been done already or it’s just not useful!
I have been getting in to using CoffeeScript recently and having written a quick extension for Radiant to allow its use, and also integrating the wonderful Ace editor I decided to do a quick post just to show how effective it can be. CoffeeScript is mark down for Javascript, two advantages to using it;
It reduces the overall amount of code you have to write,
it increases the consistency of the resulting javascript code although there is still an onus on the author to keep things tidy.
I wanted to write a small extension method to find divs with a certain class, date parse the content of the div, change the content to just the day and then apply a style based on the month.
Here is the CoffeeScript;
# jQuery function to change a div with a date in it in to a calendar
jQuery.fn.calendarify = () ->
month_names = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']
for cal_span in this
do (cal_span) ->
if !$(cal_span).hasClass 'mini-calendar'
# assign generic calendar css class to span
$(cal_span).addClass 'mini-calendar'
date = new Date cal_span.innerText
month = date.getMonth()
day = date.getDate()
$(cal_span).addClass month_names[month]
cal_span.innerText = day</pre></code>
And now for the generated javascript;
jQuery.fn.calendarify = function() {
var cal_span, month_names, _i, _len, _results;
month_names = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
_results = [];
for (_i = 0, _len = this.length; _i < _len; _i++) {
cal_span = this[_i];
_results.push((function(cal_span) {
var date, day, month;
if (!$(cal_span).hasClass('mini-calendar')) {
$(cal_span).addClass('mini-calendar');
date = new Date(cal_span.innerText);
month = date.getMonth();
day = date.getDate();
$(cal_span).addClass(month_names[month]);
return cal_span.innerText = day;
}
})(cal_span));
}
return _results;
};
I certainly prefer the former, obviously there is the occasional problem that markdown languages present but even then you can fallback and place normal javascript blocks inline with your coffeescript.
CoffeeScript lives here.