• Download Gist
jquery-assets-dispatcher.js.coffee
CoffeeScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
$ = 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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.