这是一个简单的单页小应用程序,当您按下按钮时,它会换出 4 个不同的模板和从第 1 页到第 4 页的步骤。如果您有任何问题,请告诉我。
<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>