-
-
Save rjz/3610858 to your computer and use it in GitHub Desktop.
# A class-based template for jQuery plugins in Coffeescript | |
# | |
# $('.target').myPlugin({ paramA: 'not-foo' }); | |
# $('.target').myPlugin('myMethod', 'Hello, world'); | |
# | |
# Check out Alan Hogan's original jQuery plugin template: | |
# https://github.com/alanhogan/Coffeescript-jQuery-Plugin-Template | |
# | |
(($, window) -> | |
# Define the plugin class | |
class MyPlugin | |
defaults: | |
paramA: 'foo' | |
paramB: 'bar' | |
constructor: (el, options) -> | |
@options = $.extend({}, @defaults, options) | |
@$el = $(el) | |
# Additional plugin methods go here | |
myMethod: (echo) -> | |
@$el.html(@options.paramA + ': ' + echo) | |
# Define the plugin | |
$.fn.extend myPlugin: (option, args...) -> | |
@each -> | |
$this = $(this) | |
data = $this.data('myPlugin') | |
if !data | |
$this.data 'myPlugin', (data = new MyPlugin(this, option)) | |
if typeof option == 'string' | |
data[option].apply(data, args) | |
) window.jQuery, window |
Just wanted to say this is fantastic.
+1 @adamjacobbecker
+1 thanks!
+1 this is good work!
+1 thanks!
+1 :)
+1 thank you!
fantastic thank you for putting this together!
+1 Great template! Thanks!
I have just a question, wouldn't it be better to attach the "myPlugin" data in the constructor and remove it inside a destroy method?
As I understand your code, it would be a bit akward if you want to allow the sequence
create -> destroy -> create
on the same DOM element because then the destroy method would need to remove the reference to data-myPlugin which is set outside the class if you want the second "create" to be executed.
Did I understand it right?
I would use the following to wrap the outer self-calling function.
do($ = window.jQuery, window) ->
# the rest of your code
That compiles to:
(function($, window) {
// the rest of your code
})(window.jQuery, window);
That feels more coffeescript-ish to me.
beautiful. thank you
Thanks!
Nice! I was looking for something like this!