Skip to content

Instantly share code, notes, and snippets.

@8bitDesigner
Last active December 19, 2015 07:49
Show Gist options
  • Select an option

  • Save 8bitDesigner/5921295 to your computer and use it in GitHub Desktop.

Select an option

Save 8bitDesigner/5921295 to your computer and use it in GitHub Desktop.
Simple evented ready state delegator, for cases where you don't have access to anything better.

Set up

<!-- Add this to your Rails app's body tag -->
<body data-controller="<%= request[:controller] %>" data-action="<%= request[:action] %>">

Usage

// Run a function on $.ready of every page
Loader.register(yourCallbackHere) // or
Loader.register('ready', yourCallbackHere)

// Run a function on $.ready of every page in the Welcome controller
Loader.register('welcome', yourCallbackHere)

// Only run a function on the 'index' action of the Welcome controller
Loader.register('welcome:index', yourCallbackHere)

// Run a function after every other function has run
Loader.register('ready:done', yourCallbackHere)

// Run a function on multiple controllers, actions, etc..
Loader.register(
  ['welcome', 'registration:show', 'dingus:index'],
  yourCallbackHere
)
window.Loader = Loader = { _events: {} }
Loader.register = (args...) ->
cb = args.pop()
event = if args.length then args.pop() else 'ready'
push = (e, cb) ->
Loader._events[e] = [] unless Loader._events[e]
Loader._events[e].push(cb)
if event instanceof Array then push(e, cb) for e in event
else push(event, cb)
Loader.ready = ->
controller = $('body').data('controller')
action = "#{controller}:#{$('body').data('action')}"
events = ['ready', controller, action, 'ready:done']
for event in events
cb() for cb in Loader._events[event] if Loader._events[event]
$(Loader.ready);
window.Loader = {}
Loader.register = function(/* [events], cb */) {
var args = [].slice.call(arguments)
, cb = args.pop()
, event = args.length ? args.pop() : 'ready'
function push(e, cb) {
if (!Loader._events[e]) { Loader._events[e] = [] }
Loader._events[e].push(cb)
}
if (event instanceof Array) {
$.each(event, function(i, e) { push(e, cb) })
} else {
push(event, cb)
}
}
Loader.ready = function() {
var controller = $('body').data('controller')
, action = controller +':'+ $('body').data('action')
, events = ['ready', controller, action, 'ready:done']
$.each(events, function(i, event) {
event = Loader._events[event]
if (!event || !event.length) { return }
$.each(event, function(i, cb) { cb() })
})
}
$(Loader.ready);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment