Last active
August 29, 2015 14:04
-
-
Save JonMidhir/129d270265848544f003 to your computer and use it in GitHub Desktop.
Demonstrating an example setup of a Backbone app in a Rails project with Turbolinks, from https://medium.com/p/edf4849ddb73
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
# E.g. backbone.view.js.coffee | |
Backbone.View::close = (remove = true) -> | |
if remove | |
# Remove the view element, unbinding events and destroying data | |
@remove() | |
else | |
# Undelegate events and stop listening without removing the view element | |
@undelegateEvents() | |
@stopListening() | |
# Executes a callback called onClose on the view if it exists | |
@onClose() if @onClose() | |
# Your app setup | |
window.MyApp = | |
Models: {} | |
Collections: {} | |
Views: {} | |
Routers: {} | |
initialize: -> | |
# Optional: set up a pubSub object | |
window.pubSub = _.extend({}, Backbone.Events) | |
# An example jQuery plugin that triggers events on pubSub | |
$(document).publishHotkeys(pubSub) | |
# Keep a reference to your router so you can release it later | |
@router = new MyApp.Routers.Items() | |
Backbone.history.start() | |
teardown: -> | |
# Stop jQuery plugin from publishing to pubSub | |
$(document).stopPublishingHotkeys() | |
# Clear the pubSub variable (optional) | |
window.pubSub = undefined | |
# Close the router, closing all its views and their subviews | |
@router.close() | |
# Nullify the router variable | |
@router = undefined | |
# Function determining whether the app should run on the current page | |
shouldLoadApp = -> $('#items').size() > 0 | |
# Called during the page change lifecycle, before the current page is changed | |
$(document).on 'page:before-change', -> | |
# If backbone is running and the browser supports Turbolinks | |
if Backbone.History.started and Turbolinks?.supported | |
# Replace the current state with one of Turbolinks format | |
locHref = window.location.href | |
title = window.title | |
window.history.replaceState {turbolinks: true, url: locHref}, title, locHref | |
# Called during the page change lifecycle, after the page has changed | |
$(document).on 'page:change', -> | |
# If the router is available the app needs to be torn down | |
if MyApp.router? | |
Backbone.history.stop() | |
MyApp.teardown() | |
# Initialize the app from scratch if the page requires it | |
MyApp.initialize() if shouldLoadApp() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment