Backbone 101: Routers
by kyllle
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.2/backbone-min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.3/normalize.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone-localstorage.js/1.1.16/backbone.localStorage-min.js"></script>
<h2 class="pg-heading">Routers</h2>
<p>Routers map faux-URLs to actions, and fire events when routes are matched. Creating a new one sets its routes hash, if not set statically.</p>
<a href="http://backbonejs.org/docs/backbone.html#section-183" target="_blank">Routers - Annotated Source</a>
<br>
<a href="http://addyosmani.github.io/backbone-fundamentals/#routers">Routers - Addy Osmani Backbone Fundamentals</a>
<br><br>
CSS
@import url(http://fonts.googleapis.com/css?family=Roboto:300,400,500);
* {
-webkit-font-smoothing: antialiased;
}
body {
font-family: Roboto;
padding: 16px;
line-height: 1.5;
font-weight: normal;
color: #ccc;
background: #292929;
font-size: 18px;
}
h1, h2, h3 {
font-weight: normal;
}
h3 ~ p {
margin-top: 0;
}
p {
opacity: 0.86;
}
.pg-heading {
margin-bottom: 0;
}
a {
color: #95baf6;
transition: opacity .3s;
}
a:hover {
opacity: 0.75;
}
pre {
display: block;
padding: 9.5px;
margin: 0 0 10px;
font-size: 13px;
line-height: 1.428571429;
color: #333;
word-break: break-all;
word-wrap: break-word;
background-color: #f5f5f5;
/* border: 1px solid #ccc; */
border-radius: 4px;
}
pre.app {
opacity: 0.35;
transition: opacity .3s;
position: relative;
}
pre.app:after {
content: 'App Example';
padding: 3px 8px;
background: #95baf6;
position: absolute;
top: 0;
right: 0;
border-radius: 0 4px 0 0;
}
pre.app:hover {
opacity: 1;
}
JavaScript
console.clear();
var Router = Backbone.Router.extend({
routes: {
'': 'onShowMovies',
'movie/:id': 'onShowMovie',
'movie': 'onShowMovie',
'watchlist': 'onShowWatchlist'
},
initialize: function() {
console.log('Starting Router');
},
onShowMovies: function() {
console.log('Show movies');
},
onShowMovie: function() {
console.log('Show movie', id);
},
onShowWatchlist: function() {
console.log('Show watchlist');
}
});
var router = new Router();