Trunk routing with areas

I am curious how people deal with this situation. I have an application that displays a list of categories on a route like "/ categories". When each category is clicked, a list of products of this category appears, and the route is updated approximately like this: "/ categories / 1 / products". If I navigate through several, and then click the back button, I should be able to simply visualize the product list view for the previous category without re-rendering the category view.

However, I also need to make sure that when moving directly to "/ categories / 2 / products", a list of categories is displayed, as well as a list of products.

Basically, this means that the router will have to respond differently to the reverse / redirect of history navigation than to direct access to the URL. Is there a general solution to this problem?

+6
source share
1 answer

Yes, sections of children should always be called after the parent has been created, it does not matter if it was accessible by a direct URL or through navigation on the router.

My workaround for this is always the main view in my applications, and the router always calls this main view. The router does not have access to other views. In my main view, I could handle the case when a parent view is created or not.

Example, check how the router only calls MainView, and there I have a method called validateCategories that creates the parent view, if necessary:

var MainView = Backbone.View.extend({ id : 'mainView', categories : null, events : { }, initialize : function(){ _.bindAll(this); }, openSection : function(section){ switch(section){ case 'categories': this.validateCategories(); break; case 'products': this.validateCategories(); this.categories.open( new ProductsView() ); break; } }, validateCategories : function(){ if( !this.categories ){ //we create the parent view only if not yet created this.categories = new CategoriesView(); } } }); var mainView = new MainView(); var RouterClass = Backbone.Router.extend({ routes : { "categories" : "viewCategories", "categories/:id/:section" : "viewProducts" }, viewCategories : function(path) { mainView.openSection( 'categories' ); }, viewProducts : function(id, section){ mainView.model.set({ productId : id, section : section, }); mainView.openSection( 'products' ); } }); 

Also, if you start from scratch, a new project do not forget to look at this extension, which will help you organize Backbone.js projects: https://github.com/derickbailey/backbone.marionette

+5
source

Source: https://habr.com/ru/post/920456/


All Articles