How do I create a jQuery plugin in CoffeeScript?

On How to Create a Basic Plugin there is a section titled Protecting the $ Alias and Adding Scope.

The $ variable is very popular among JavaScript libraries, and if you're using another library with jQuery, you will have to make jQuery not use the $ with jQuery.noConflict(). However, this will break our plugin since it is written with the assumption that $ is an alias to the jQuery function. To work well with other plugins, and still use the jQuery $ alias, we need to put all of our code inside of an Immediately Invoked Function Expression, and then pass the function jQuery, and name the parameter $:

In JavaScript, this wrapper looks like this:

(function ( $ ) {
  // do stuff
  return this;
})(jQuery)

How can this be translated into CoffeeScript?

Answers


This coffeescript:

$ = jQuery
### do stuff ###

compiles to:

// Generated by CoffeeScript 1.6.3
(function() {
  var $;
  $ = jQuery;
  /* do stuff*/
}).call(this);

I think the effect is the same, ensuring that $ points to jQuery regardless of what $ is in the calling environment.

This is what the author of Coffeescript recommends in Writing a jquery plugin in coffeescript - how to get "(function($)" and "(jQuery)"?

To get closer to the original pattern (do is still something of a blackbox to me)

do ($=jQuery) ->
  ### do stuff  ###
  @

'bare' compiles to:

// Generated by CoffeeScript 1.6.3
(function($) {
  /* do stuff*/

  return this;
})(jQuery);

Need Your Help

Checkbox not binding properly

.net asp.net-mvc checkbox model-binding

I'm having the following problem with my program:

Create resizable/multiline Tkinter/ttk Labels with word wrap

python windows tkinter ttk

Is it possible to create a multi-line label with word wrap that resizes in sync with the width of its parent? In other words the wordwrap behavior of Notepad as you change the width of the NotePad

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.