Let's say I have a search form at /search
with a QueryView
representing the search form. When the user submits a query, I would like to route to /results
and add a ResultView
for the results, keeping the QueryView
in case the user wants to do a new search.
Then, if the user navigates directly to /results
, I have to create both the QueryView
and the ResultsView
in the route function. The problem is that I'd like the behavior in the /search
and /results
routes to be the same, but have to remember to make any changes in both places.
An alternative is to trigger the route for /results
when the user submits, which will destroy the existing QueryView
and create a new QueryView
and ResultView
. This works, but destroying and recreating the QueryView
causes some annoyances in my case.
Are there standard design patterns to persist views across routes, without having code to create the view in two places?
I wound up writing a ViewManager class to handle persisting views across routes. Example usage:
// On load
var FooView = Backbone.View.extend({ ... });
var BarView = Backbone.View.extend({ ... });
var vm = new ViewManager({selector: ".content");
// On route
var foo = vm.getView(FooView, {}, true);
vm.showViews([foo]);
// On another route
var foo = vm.getView(FooView, {}, true);
var bar = vm.getView(BarView, {}, true);
vm.showViews([foo, bar]);