Skip to content

Instantly share code, notes, and snippets.

@danmartens
Last active December 20, 2015 11:19
Show Gist options
  • Save danmartens/6122958 to your computer and use it in GitHub Desktop.
Save danmartens/6122958 to your computer and use it in GitHub Desktop.
jQuery plugin pattern that attaches a class instance to the element. Inspired by http://coding.smashingmagazine.com/2011/10/11/essential-jquery-plugin-patterns.
(($) ->
pluginName = 'pluginName'
defaults = {
prop: 'value'
}
class Plugin
constructor: (element, options) ->
@el = element; @$el = $(element)
@options = $.extend({}, defaults, options)
@init()
init: ->
# intialization stuff goes here
$.fn[pluginName] = (optionsOrMethod) ->
@each ->
plugin = $.data(this, "plugin_#{pluginName}")
if typeof optionsOrMethod is 'object'
unless plugin
$.data(this, "plugin_#{pluginName}", new Plugin(this, optionsOrMethod))
else
plugin[optionsOrMethod](Array::slice.call(arguments, 1))
)(jQuery)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment