Skip to content

Instantly share code, notes, and snippets.

@tdreyno
Created May 13, 2011 06:11
Show Gist options
  • Save tdreyno/970069 to your computer and use it in GitHub Desktop.
Save tdreyno/970069 to your computer and use it in GitHub Desktop.
Work in Progress CoffeeScript Widget Factory
# Base widget class
class Widget
@widgetClass: 'widget_base'
@defaults: {}
# Apply options and data() options to defaults hash
constructor: (@$element, options={}) ->
# The descendent constructor
actualConstructor = @__proto__.constructor
@options = @_getDefaults actualConstructor, options
# Add a class to the entire widget
@$element.addClass actualConstructor.widgetClass
# Compile the defaults for this level
_getDefaults: (scope, overrides) ->
opts = {}
for key, value of scope.defaults
opts[key] = @$element.data(key) || value
for key, value of overrides
opts[key] = value
if scope.__super__?.constructor.defaults
@_getDefaults(scope.__super__.constructor, opts)
else
opts
# Bind events in class scope convenience method
_bind: (scope, eventName, callbackName) ->
self = this
scope.bind eventName, (evt) -> self[callbackName](evt, this)
@setupPlugin: () ->
name = @widgetClass
classConstructor = @
$.fn[name] = (options) ->
@each ->
$elem = $ this
$elem.data(
name
new classConstructor $elem, options
) if not $elem.data name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment