2

What I would like is a route that can handle all the following routes in 1 line.

Currently it looks like this:

routes: {
'item': 'itemConsole',
'item/view/:workflowId': 'itemDetail',
'item/create': 'itemCreate',
'item/create/:templateId': 'itemCreate',
'item/task/:taskId': 'itemTask',
'item/metrics': 'itemMetrics',
'item/notAccessible': 'itemNotAccessible',
}

I would like to condense that down to something using the splat(*) as mentioned here

This works 'item(*thing)': 'itemController' but the controller gets passed a single string that I would then have to split and what not. I'd rather it pass them as parameters (action, id) to my controller not a single string param.

Mike Fielden
  • 10,055
  • 14
  • 59
  • 99

1 Answers1

1

Optional parts in your route (/:optional) could do the trick:

var Router = Backbone.Router.extend({
    routes: {
        'item(/:action)(/:id)': 'itemController'
    },

    itemController: function (action, id) {
        console.log(action, id);
    }
});

var Router = Backbone.Router.extend({
    routes: {
        'item(/:action)(/:id)': 'itemController'
    },

    itemController: function (action, id) {
       $('#log').append(JSON.stringify({
         action: action,
           id: id
        }));
    }
});

new Router();
Backbone.history.start();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="http://backbonejs.org/backbone-min.js"></script>

<a href='#item'>#item</a>
<hr />
<a href='#item/view'>#item/view</a>
<hr />
<a href='#item/view/1'>#item/view/1</a>
<hr />
<a href='#item/create'>#item/create</a>
<hr />
<a href='#item/create/2'>#item/create/2</a>

<div id='log'></div>
nikoshr
  • 32,926
  • 33
  • 91
  • 105
  • Perfect. And well answered. Thanks. I got it closer by doing this `item(/:action(/:id))` but your answer is much nicer – Mike Fielden Sep 18 '14 at 17:39