Backbone.jsのRouter
Backboneについて何か書こう書こうと思ってたけど、長くなってしまいがちで、長い文章は苦手なので下書きがたまるいっぽうだったんだけど、簡単なやつから書いていきましょうかなみたいな
Routerを使うと、hashchangeを監視してroutesに記述したルールに沿ってルーティングしてくれる。:slugみたいにすると、functionの引数でslugが受け取れるのでよしなにする感じ。newしたときに、initializeが1回、URLに応じたルーティングが一回走るので、ここに_gaq.pushしてる場合は、index.htmlに入れているtrackPageviewを削除しておいたほうがよさそう。
// setup var Router = Backbone.Router.extend({ routes: { '' : 'root', 'log/:slug' : 'day', 'about' : 'about' }, initialize: function() { // init }, root: function() { // http://example.com/ // or // http://example.com/# }, log: function(slug) { // http://example.com/#log/hoge }, about: function() { // http://example.com/#about } }); // nanika... // init new Router(); Backbone.history.start();
その場で実行してしまいたいときはこんな感じ
// setup new (Backbone.Router.extend({ routes: { '' : 'root', ... }, ... })); Backbone.history.start();
オプション指定でpushStateを利用できます
Backbone.history.start({ pushState: true });
ってこれ、全部ドキュメントに書いてあるけどね