手間のかからない解決策として、viewメソッドをイベントに直接バインドできます。router:route
イベントは、ルーターが定義されたルートへのURL変更を照合するたびに発生します。
var QuestionsView = Backbone.View.extend({
initialize: function(){
this.listenTo(yourRouter, 'route', this.navigateAway);
)
});
これはうまくいくはずですが、私にはスパゲッティのように感じます。
私は通常onBeforeClose
、ビューにメソッドを実装しました。このメソッドは、現在のビューから移動する前に呼び出します。次のようになります:
var Router = Backbone.Router.extend({
navigateToView: function(view) {
//I've actually abstracted this logic to a separate
//view manager class, but you get the idea...
var current = this.currentView;
if(current) {
if(current.onBeforeClose)
current.onBeforeClose();
current.remove();
}
this.currentView = view;
//render your current view here, however you like
$(body).html(this.currentView.render().el);
},
someRoute: function() {
var view = new SomeView();
this.navigateToView(view);
}
});
それは何よりも慣習です。ビューにメソッドがない場合、そのビューはonBeforeClose
呼び出されず、害はありません。
これには、1つの集中化された方法(この場合)を使用してビューをレンダリングする必要があることに注意してください。ただし、関係なくnavigateToView
を使用して古いビューをクリーンアップする必要があるため、これは良いことですremove
。