今回はRouterの紹介です。これを使うと、画面遷移を実現でき、ブラウザの戻るボタンの制御もできます。
以下の機能を提供します。
トップとメインの2画面を用意してみます。
var TopView = Backbone.View.extend({
el : '#container',
// 中略
};
var MainView = Backbone.View.extend({
el : '#container',
// 中略
};
var AppRounter = Backbone.Router.extend({
routes : {
"" : "top",
"main" : "main"
},
initialize : function() {
_.bindAll(this, 'top', 'main');
this.topView = new TopView();
this.mainView = new MainView();
},
top : function() {
this.topView.render();
},
main : function() {
this.mainView.render();
}
});
var app = {};
$(function() {
app.router = new AppRounter();
Backbone.history.start();
});
routesで、URLのパターンでどの関数を呼ぶかの対応を指定します。各関数では、Viewのrender()メソッドを呼ぶことで、画面の差し替えを実現しています。
ready()で、AppRouterオブジェクトを作成し、Backbone.history.start()を呼びます。これで履歴の監視が始まります。
画面遷移は、必要な場面でAppRouterオブジェクトのnavigate()メソッドを呼びます。
app.router.navigate('main', {trigger:true});