index.html
<!doctype html>
<head>
<meta charset="utf-8">
<title>Backbone.js Routes Example</title>
<link rel="stylesheet" href="assets/css/bootstrap-1.2.0.min.css" />
<link rel="stylesheet" href="assets/css/styles.css" />
<script src="assets/js/jquery-1.6.4.min.js"></script>
<script src="assets/js/underscore-min.js"></script>
<script src="assets/js/backbone-min.js"></script>
<script src="assets/js/application.js"></script>
</head>
<body>
<ul class="route">
<li class="home-route"><a>Home</a></li>
<li class="about-route"><a>About</a></li>
<li class="contact-route"><a>Contact</a></li>
</ul>
<div id="home-page" class="pages">Hi I'm the home page!</div>
<div id="about-page" class="pages">Hi I'm the about page!</div>
<div id="contact-page" class="pages">Hi I'm the contact page!</div>
</body>
</html>
$(function(){
var ApplicationRouter = Backbone.Router.extend({
//map url routes to contained methods
routes: {
"": "home",
"home": "home",
"about": "about",
"contact": "contact"
},
deselectRoutes: function(){
//deselect all navigation Routes
$('ul.route li').removeClass('active');
},
selectRoutes: function(Routes){
//deselect all navigation Routes
this.deselectRoutes();
//select passed navigation Routes by selector
$(Routes).addClass('active');
},
hidePages: function(){
//hide all pages with 'pages' class
$('div.pages').hide();
},
showPage: function(page){
//hide all pages
this.hidePages();
//show passed page by selector
$(page).show();
},
home: function() {
this.showPage('div#home-page');
this.selectRoutes('li.home-route');
},
about: function() {
this.showPage('div#about-page');
this.selectRoutes('li.about-route');
},
contact: function() {
this.showPage('div#contact-page');
this.selectRoutes('li.contact-route');
}
});
var ApplicationView = Backbone.View.extend({
//bind view to body element (all views should be bound to DOM elements)
el: $('body'),
//observe navigation click events and map to contained methods
events: {
'click ul.route li.home-route a': 'displayHome',
'click ul.route li.about-route a': 'displayAbout',
'click ul.route li.contact-route a': 'displayContact'
},
//called on instantiation
initialize: function(){
//set dependency on ApplicationRouter
this.router = new ApplicationRouter();
//call to begin monitoring uri and route changes
Backbone.history.start();
},
displayHome: function(){
//update url and pass true to execute route method
this.router.navigate("home", true);
},
displayAbout: function(){
//update url and pass true to execute route method
this.router.navigate("about", true);
},
displayContact: function(){
//update url and pass true to execute route method
this.router.navigate("contact", true);
}
});
//load application
new ApplicationView();
});
No comments:
Post a Comment