-
-
Save harmdewit/f1b74976a91dc574907a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 | |
# | |
do ($ = window.jQuery, window, document) -> | |
pluginName = 'pluginName' | |
# Define the plugin class | |
class Plugin | |
defaults: | |
paramA: 'foo' | |
paramB: 'bar' | |
constructor: (el, options) -> | |
@options = $.extend({}, @defaults, options) | |
@$el = $(el) | |
@init() | |
init: -> | |
# Place initialization logic here | |
# You already have access to the DOM element and the options via the instance, | |
# e.g., @element and @settings | |
# Additional plugin methods go here | |
myMethod: (echo) -> | |
@$el.html(@options.paramA + ': ' + echo) | |
# Define the plugin | |
# A really lightweight plugin wrapper around the constructor, | |
# preventing against multiple instantiations | |
$.fn[pluginName] = (option, args...) -> | |
@each -> | |
$this = $(this) | |
data = $this.data("plugin_#{pluginName}") | |
if !data | |
$this.data "plugin_#{pluginName}", (data = new Plugin(this, option)) | |
if typeof option == 'string' | |
data[option].apply(data, args) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment