Skip to content

Instantly share code, notes, and snippets.

@andreapavoni
Created March 1, 2013 14:17
Show Gist options
  • Save andreapavoni/5064928 to your computer and use it in GitHub Desktop.
Save andreapavoni/5064928 to your computer and use it in GitHub Desktop.
A basic example to show how to implement simple/clean jQuery plugins with CoffeeScript
# jQuery custom plugin skeleton with CoffeeScript
class MyPlugin
someMethod: (args) ->
# do something
constructor: (element, params) ->
@someMethod(some_args)
# do something
# install in the window namespace
window.MyPlugin = MyPlugin
# create jQuery plugin
$.fn.myPlugin = (params) ->
new MyPlugin($(@), params)
return $(@)
# Usage:
# $('#element').myPlugin(params)
@stecb
Copy link

stecb commented Mar 1, 2013

No prob ;)

About defaults, right u can, but in that case u would have the same defaults for each MyPlugin instance. Isn't better to define them just once? and maybe, if u need to overwrite them for a particular element, just define a more specific selector i.e.

$('#myselector#').myPlugin(someOptions)

$('#myOtherSelector#').myPlugin(someOtherOptions)

By defining a namespace I think it's more clear 'coz (if you don't want to use the global window - or you have a custom ns) u just have to pass your custom namespace to the closure without checking where you're using it (ok, u're using it just once and it's fairly immediate to substitute it, but imagine a more complicated scenario where u have multiple use of a namespace).. btw, this is just a small improvement and in this case can be omitted :)

About your questions:

  • Yes it's targetting jQuery .. but what if u (or users that will use your plugin) include that plugin within a noConflict env? it's always recommended, when u write a plugin, to use this technique (basically $ is used by some other lib and u don't rely on $ as a shortcut for jQuery, so u are forced to use jQuery). Moreover, a local var ($ in that case) is slightly faster than accessing a global var.
  • It's useful when you want i.e. to change in real time a property of that plugin and refresh it by calling a public method of MyPlugin instance

@andreapavoni
Copy link
Author

(again) nice points, thanks! :-)

I'll think about your concepts and way to integrate them with my approach, you're right (and yes, I'm still a sort-of-noob on this topic :P).

thanks! (repetita iuvant)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment