Last active
August 29, 2015 14:06
-
-
Save tylerjohnst/887fb57b254d7f293bde to your computer and use it in GitHub Desktop.
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
# my_file.coffee | |
# | |
# view = null | |
# | |
# ready controllers: ['sessions'], -> | |
# view = new Backbone.View() | |
# view.renderAndAppendTo('#my-widget') | |
# | |
# unload controllers: ['sessions'], -> | |
# view.remove() | |
# | |
# Callback that runs when the page is "ready" with Turbolinks. Use this to ensure the function is rerun on page reload. | |
window.ready = (options, callback) -> | |
lifecycle.on('ready', options, callback) | |
# Callback that runs before the page is replaced by Turbolinks. Use this to ensure references are cleaned up. | |
window.unload = (options, callback) -> | |
lifecycle.on('unload', options, callback) | |
# Have to trigger this as on a regular page load since thats not under turbolinks. | |
$ -> lifecycle.dispatchEventsFor('ready') | |
class TurbolinksLifecycle | |
CALLBACKS = | |
ready: 'page:load' | |
unload: 'page:fetch' | |
DEFAULT_OPTIONS = | |
controllers: [] | |
constructor: -> | |
this.reset() | |
this._listenToTurbolinks() | |
reset: -> | |
this._events = | |
ready: [] | |
unload: [] | |
on: (lifecycleEventName, options, callback) -> | |
if callback is undefined | |
callback = options | |
options = {} | |
options = $.extend(DEFAULT_OPTIONS, options) | |
this._events[lifecycleEventName].push(options: options, callback: callback) | |
dispatchEventsFor: (lifecycleEventName) => | |
for binding in this._events[lifecycleEventName] | |
binding.callback() if this._shouldTrigger(binding.options) | |
_listenToTurbolinks: -> | |
$(document).on CALLBACKS.ready, (jqEvent) => this.dispatchEventsFor('ready') | |
$(document).on CALLBACKS.unload, (jqEvent) => this.dispatchEventsFor('unload') | |
_shouldTrigger: (options) -> | |
return true if options.controllers.length is 0 | |
return this._controllerName() in options.controllers | |
_controllerName: -> | |
return window.ENV.controller | |
window.lifecycle = new TurbolinksLifecycle() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment