Backbone.js: routing for nested views

I am trying to figure out the following scenario:

Suppose I have two types: one for viewing items and one for purchasing them. The trick is that viewing a purchase is an optional view for viewing.

For routing, I have:

var MyRouter = Backbone.Router.extend({ routes: { 'item/:id': 'viewRoute', 'item/:id/buy': 'buyRoute' } }); var router = new MyRouter; router.on("route:viewRoute", function() { // initialize main view App.mainview = new ViewItemView(); }); router.on("route:buyRoute", function() { // initialize sub view App.subview = new BuyItemView(); }); 

Now, if the user refreshes the page and buyRoute starts up, but now there is no main view. What would be the best solution for this?

+6
source share
2 answers

I believe that the problem you are currently facing is that you do not want to show some things inside the ViewItem inside the BuyView? If so, then you should modulate what BuyView and ViewItem have in common with the other view, and then initialize it on both of these routes.

Here is a sample code from one of my applications

https://github.com/QuynhNguyen/Team-Collaboration/blob/master/app/scripts/routes/app-router.coffee

As you can see, I modulated the sidebar, as it can be shared between many views. I did this so that it can be reused and not cause conflicts.

0
source

You can simply check for the presence of the main view and create / open it if it does not already exist.

I usually create (but do not open) the main types of my application when the application loads, and then some kind of view manager for opening / closing. For small projects, I just bind my views to the views property of my application object, so that they are all in one place, available as view.mainView, views.anotherView, etc.

I also extend Backbone.View in two ways: open and close , which not only adds / removes the view to / from the DOM, but also sets the isOpen flag in the view.

With this, you can check if an already open view is open, and then open it if not, for example:

 if (!app.views.mainView.isOpen) { // } 

An additional addition would be to create a method in your application called clearViews that clears any open views, possibly with the exception of the names of the views passed as parameters to clearViews . Therefore, if you have a navigation view that you do not want to delete on some routes, you can simply call app.clearViews('topNav') and all views except views.topNav will be closed.

check this meaning for the whole code: https://gist.github.com/4597606

0
source

All Articles