Marionette Regions and routing

94 views Asked by At

I'm using a LayoutView to display a collection in table form. When a user clicks on a tr I swap the CompositeView for an ItemView that shows the details using the same region. It all works except the functionality of the back button is broken. Is there a way to trap the back event and switch views?

Or should I use two Views and pass the model id and then refetch the model? The problem with that though is the extra request and I lose the filter and sort values of the table unless I use local storage.

1

There are 1 answers

0
Gabo On

Including more code would be better, but in any case I will try to give some guidance for your problem.

To avoid fetching the data twice, you can keep a common object in a "parent" component, for example in the Router.

 var theObject;
 var router = Marionette.AppRouter.extend({
   routes: {
    "routeA/:id": "goToRouteA",
    "routeB/:id": "goToRouteB"
   },
   goToRouteA: function(id) {
     MyRegion.show(new myLayout({
       model: this._getCommonObject(id)
     }));
  },
  goToRouteB: function(id) {
     MyRegion.show(new myLayout({
       model: this._getCommonObject(id)
     }));  
  },
  /*Return the common object for the views*/
  _getCommonObject: function(id) {
    theObject = (theObject && theObject.get('id') == id) ? theObject : MyApp.request('getTheObject'); 
    return theObject;
  }
});

In this way, you can keep the reference to the same object without loosing information.

You just have to make sure to delete the object when it is not needed to avoid keeping old information, for example on the Region close event.