-
-
Save andreapavoni/5064928 to your computer and use it in GitHub Desktop.
# 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) |
nice points, thanks! :-)
I was showing a very simple approach. I can still apply defaults (eg: inside constructor) and I might remove the namespace part, it will work anyway.
2 questions:
- why do you pass jQuery? That code is already targetting jQuery, am I missing anything? :P
- why do you save a plugin instance? I mean, do you have any use case for that?
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 forjQuery
, so u are forced to usejQuery
). 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
(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)
I would add defaults and a namespace, and I'd apply the plugin for each element (if your selector matches more than 1 elem) i.e.