Skip to content

Instantly share code, notes, and snippets.

@mralexgray
Forked from rjz/cs-jq-plugin-template.coffee
Last active June 9, 2016 03:24
Show Gist options
  • Save mralexgray/958933c30b2b67be0e2c63b5bf2ce4a5 to your computer and use it in GitHub Desktop.
Save mralexgray/958933c30b2b67be0e2c63b5bf2ce4a5 to your computer and use it in GitHub Desktop.
Coffeescript jQuery Plugin Class Template
# 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) ->
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment