Routing in Backbone.js
Simple example of routing in Backbone.js
by Danish Farman
HTML
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
<div id="navigation">
<a href="#/home">Home</a>
<a href="#/about">About</a>
</div>
<div id="content">
</div>
SCSS
body { margin: 30px;}
body {font-family: Arial;}
h1{font-weight:bold;font-size:16px;}
p{margin:5px 0px 5px 0px;}
div{margin:15px;}
div a{margin:5px;}
JavaScript
var HomeView = Backbone.View.extend({
template: '<h1>Home</h1>',
initialize: function () {
this.render();
},
render: function () {
this.$el.html(this.template);
}
});
var AboutView = Backbone.View.extend({
template: '<h1>About</h1>',
initialize: function () {
this.render();
},
render: function () {
this.$el.html(this.template);
}
});
var AppRouter = Backbone.Router.extend({
routes: {
'': 'homeRoute',
'home': 'homeRoute',
'about': 'aboutRoute',
},
homeRoute: function () {
var homeView = new HomeView();
$("#content").html(homeView.el);
},
aboutRoute: function () {
var aboutView = new AboutView();
$("#content").html(aboutView.el);
}
});
var appRouter = new AppRouter();
Backbone.history.start();