Skip to content

Instantly share code, notes, and snippets.

@polarblau
Created February 11, 2013 13:08
Show Gist options
  • Save polarblau/4754326 to your computer and use it in GitHub Desktop.
Save polarblau/4754326 to your computer and use it in GitHub Desktop.
Base for new jQuery plugins written in Coffeescript. Enables plugin methods. Based on http://coffeescriptcookbook.com/chapters/jquery/plugin and http://docs.jquery.com/Plugins/Authoring#Plugin_Methods .
$ = jQuery
$.fn.extend
foobar: (method) ->
settings =
option1: true
option2: false
localMethod = ->
console.log "Local method called!"
apiMethods =
init: (options) ->
settings = $.extend true, settings, options
console.log "Initialized!"
localMethod() # "private" methods
console.log $(@).attr 'id' # scope, this = DOM element
console.log "Option 1: #{settings.option1}" # options
destroy: ->
console.log "Destroyed!"
if apiMethods[method]?
apiMethods[method].apply @, Array.prototype.slice.call(arguments, 1)
else if typeof method is 'object' or !method
apiMethods.init.apply @, arguments
else
$.error "jQuery.foobar doesn't implement the method '#{method}'."
$('#foo').foobar(option1: false)
# -> Initialized!
# -> Local method called!
# -> foo
# -> Option 1: false
$('#bar').foobar('destroy')
# -> Destroyed!
$('#bat').foobar('foo')
# -> Uncaught Error: jQuery.foobar doesn't implement the method 'foo'.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment