Created
February 11, 2013 13:08
-
-
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 .
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
$ = 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}'." |
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
$('#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