Forked from mashiro/jquery-assets-dispatcher.js.coffee
Created
January 18, 2012 19:52
-
-
Save Epictetus/1635150 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
class Bucket | |
constructor: (@name = "__root__", @children = {}, @actions = {}) -> | |
getCallbacks: (actions...) -> | |
callbacks = [] | |
Array::push.apply(callbacks, @actions[action] || []) for action in actions | |
return callbacks | |
setCallback: (action, callback) -> | |
callbacks = @actions[action] ||= [] | |
callbacks.push callback | |
class AssetsDispatcher | |
constructor: (@root = new Bucket) -> | |
on: (options, callback) -> | |
data = @_parse options.controller, options.action | |
bucket = @root | |
bucket = (bucket.children[controller] ||= new Bucket(controller)) for controller in data.controllers | |
bucket.setCallback data.action, callback | |
return bucket | |
dispatch: (selector = "body", options = {}) -> | |
elem = $(selector) | |
controller = if options.controller? then options.controller(elem) else elem.data("controller") | |
action = if options.action? then options.action(elem) else elem.data("action") | |
data = @_parse controller, action | |
callbacks = [] | |
@_dispatch @root.children, data.controllers, data.action, callbacks | |
callback(controller, action) for callback in callbacks | |
return callbacks.length > 0 | |
_dispatch: (buckets, controllers, action, callbacks) -> | |
controller = controllers.shift() | |
@_dispatch buckets, [""], action, callbacks if controller != "" | |
bucket = buckets[controller] | |
if bucket? | |
Array::push.apply(callbacks, bucket.getCallbacks("", action)) | |
#console.log "check: C[#{controller}] A[#{action}]" | |
#console.log callbacks | |
@_dispatch bucket.children, controllers, action, callbacks if controller != "" | |
_parse: (controller, action) -> | |
data = {} | |
data.controllers = $.trim(controller).split(" ") unless controller instanceof Array | |
data.action = $.trim(action) | |
data | |
$.assets = new AssetsDispatcher |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment