Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js: Routing for nested views

I'm trying to figure out following scenario:

Lets say that I have two views: one for viewing items and one for buying them. The catch is that buying view is a sub 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 user refreshes the page and buyRoute gets triggered but now there is no main view. What would be best solution to handle this?

like image 627
Fdr Avatar asked Jan 22 '13 14:01

Fdr


1 Answers

I am supposed that the problem you are having right now is that you don't want to show some of the stuff inside ViewItem inside BuyView? If so then you should modularized what BuyView and ViewItem have in common into another View then initialize it on both of those routes.

Here is a code example from one of my apps

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

As you can see, I modularized out the sidebar since it can be shared among many views. I did that so that it can be reused and won't cause any conflicts.

like image 183
Infinity Avatar answered Nov 02 '22 06:11

Infinity