JavaScript は他のコードと同じです。同じコード行を書いている場合は、それらを関数に抽出します。同じ関数を使用する必要がある場合は、それ (および関連する関数とデータ) を独自のオブジェクトに抽出します。
したがって、ルーターがビューとモデルを直接呼び出すべきではありません。代わりに、ビューとオブジェクトを操作できる他のオブジェクトに委任する必要があります。
さらに、アプリが起動するたびに同じ基本的なページ レイアウトを設定するため、ルーターにそのコードが必要ない場合があります。レイアウトは、ルーターが起動するかどうかに関係なく、どのルートが起動されるかに関係なく発生します。場合によっては、レイアウト コードを別のオブジェクトにも配置し、ルーターが起動する前にレイアウトを配置する方が簡単です。
MyApplication = {
layout: function(){
var v1 = new View1();
v1.render();
$("something").html(v1.el);
var v2 = new View2();
v2.render();
$("#another").html(v2.el);
},
doSomething: function(value){
// do someething with the value
// render another view, here
var v3 = new View3();
v3.render();
$("#whatever").html(v3.el);
}
}
MyRouter = Backbone.Router.extend({
routes: {
"some/route/:value": "someRoute"
},
someRoute: function(value){
MyApplication.doSomething(value);
}
});
// start it up
MyApplication.layout();
new MyRouter();
Backbone.history.start();
私はこれらのことに関連するいくつかの記事を書いています。
http://lostechies.com/derickbailey/2012/02/06/3-stages-of-a-backbone-applications-startup/
http://lostechies.com/derickbailey/2011/08/30/dont-limit-your-backbone-apps-to-backbone-constructs/
http://lostechies.com/derickbailey/2011/12/27/the-responsions-of-the-various-pieces-of-backbone-js/
http://lostechies.com/derickbailey/2012/03/22/managing-layouts-and-nested-views-with-backbone-marionette/