これは、ボタンを押すと 4 つの異なるテンプレートとページ 1 から 4 を切り替えるシンプルな小さな 1 ページのアプリです。ご不明な点がございましたら、お知らせください。
<html>
<head>
<title>Steps</title>
<script src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js"></script>
<script type="text/x-template" id="page-1">
<p>Page one content</p>
</script>
<script type="text/x-template" id="page-2">
<p>Page two content</p>
</script>
<script type="text/x-template" id="page-3">
<p>Page three content</p>
</script>
<script type="text/x-template" id="page-4">
<p>Page four content</p>
</script>
<script>
(function($){
// Helper to get template text.
function getTemplate(index){
return $('#page-' + index).text();
}
// Simple view to render a template, and add a button that
// will navigate to the next page when clicked.
var PageView = Backbone.View.extend({
index_: null,
events: {
'click button': 'nextPage_'
},
initialize: function(options){
this.index_ = options.index;
},
render: function(){
var html = getTemplate(this.index_);
// If there is a next page, add a button to proceed.
if (html && getTemplate(this.index_ + 1)){
html += '<button>Next</button>';
}
this.$el.html(html);
},
nextPage_: function(){
router.navigate('page/' + (this.index_ + 1), {trigger: true});
}
});
// Router handling a default page, and the page urls.
var Router = Backbone.Router.extend({
routes: {
'page/:index': 'loadPage',
'*notFound': 'defaultPage'
},
defaultPage: function(){
this.loadPage();
},
loadPage: function(index){
// Default to page 1 when no page is given.
index = parseInt(index, 10) || 1;
if (this.pageView_) this.pageView_.remove();
this.pageView_ = new PageView({index: index});
this.pageView_.render();
this.pageView_.$el.appendTo('#content');
}
});
var router;
$(function(){
router = new Router();
Backbone.history.start({pushState: true});
});
})(jQuery);
</script>
</head>
<body>
<!-- Some page header -->
<section id="content"></section>
</body>
</html>