Skip to content

Instantly share code, notes, and snippets.

@craigmdennis
Forked from rjz/cs-jq-plugin-template.coffee
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save craigmdennis/78c7622881bd6aa21b75 to your computer and use it in GitHub Desktop.
Save craigmdennis/78c7622881bd6aa21b75 to your computer and use it in GitHub Desktop.
A class-based template for jQuery plugins in Coffeescript
# $('.target').myPlugin();
# $('.target').myPlugin({ paramA: 'not-foo' });
# $('.target').myPlugin('myMethod', 'Hello, world');
do($ = window.jQuery, window) ->
# Define the plugin class
class MyPlugin
defaults:
paramA: 'foo'
paramB: 'bar'
# Construct / init the plugin
constructor: (el, options) ->
@options = $.extend({}, @defaults, options)
@$el = $(el)
@bind()
# Bind event handlers
bind: ->
@$el.on 'click', ->
console.log 'Clicked'
# 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