Skip to content

Instantly share code, notes, and snippets.

@renancarvalho
Last active August 29, 2015 14:01
Show Gist options
  • Save renancarvalho/d2a0d403e230aa033552 to your computer and use it in GitHub Desktop.
Save renancarvalho/d2a0d403e230aa033552 to your computer and use it in GitHub Desktop.
Setting up your single page application using Backbone + Require using CoffeeScript
<!DOCTYPE html>
<html>
<head>
@* Load your css files here *@
</head>
<body>
<section id='app'></section>
</body>
@* The init.js it's a Coffee File that handle all the configurations to load your js modules *@
<script data-main="../scripts/init.js" src="~/scripts/libs/require.min.js"></script>
</html>
require.config
# base url will be used as a 'root' path to load your modules
# you can also use path's like http:// ..
baseUrl: 'scripts'
paths:
jquery: 'libs/Jquery-2.0.2'
Backbone: 'libs/backbone'
handlebars: 'libs/handlebars'
underscore: 'libs/underscore'
BackboneValidation: 'libs/backbone-validation-min'
BackboneValidationBootstrap: 'libs/backbone-validation-bootstrap'
# use shim to declare the dependecies of files, for example, backbone depends on underscore and jquery,
# so they need to be loaded before backbone loads, and if you'd like to use them in a global namespace, you use 'exports'.
shim:
Backbone:
deps: ['underscore','jquery']
exports: 'Backbone'
BackboneValidationBootstrap:
deps:["BackboneValidation"]
BackboneValidation:
deps: ["Backbone"]
exports: 'BackboneValidation'
# Here we start our backbone router(to work, you need to have a js file called router in your base url path,
# in this case scripts/router.js
# calling Backbone.history.start, backbone will start monitor for your url changes.
require ["Router"], (Router)->
router = new Router()
Backbone.history.start()
#Loading our modules.
define [
"Backbone"
"views/HomeView"
"views/Login/LoginView"
"views/welcome/WelcomeView"
], (Backbone, HomeView, LoginView, WelcomeView) ->
class AppRouter extends Backbone.Router
initialize:->
# jquery selector to populate mainEl with out section tag.
@mainEl = $("#app")
# configure your routes
# example, http://localhost:3000/#login, will call the login function, to render the view login.
routes:->
#default route
'':'renderHome'
'login' : 'renderLoginView'
'welcome' : 'renderWelcomeNewUser'
renderHome:->
homeView = new HomeView(el:@mainEl)
renderLoginView:->
loginView = new LoginView(el:@mainEl)
renderWelcomeNewUser:->
welcomeView = new WelcomeView(el:@mainEl)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment