1

I want to have a kind of RESTful URL structure like below:

  • /accounts
  • /accounts/account/123

I've set up my routes as such:


    MyRouter = Backbone.Router.extend({

        routes : {
            '/accounts':                         'accounts',
            '/accounts/account/:account':        'account',
        },
        accounts: function() {
            console.log('accounts CALLED');
        },
        account: function() { 
            console.log('account CALLED');
        },
    });

The problem, is when I go to /accounts/account/123 , both accounts() and account() get called (as the URL matches both routes). I tried a route such as /accounts$, but it doesn't look like it's supported in the routes hash.

Is there a way to accomplish this? Would a manual router.route(route, name, callback) work instead (although I really prefer not to do that).

Nutritioustim
  • 2,686
  • 4
  • 32
  • 57
  • Have you tried: `routes : { '/accounts/account/:account': 'account', '/accounts': 'accounts' },` I.E. flipping them around? – Esailija Nov 26 '11 at 18:33
  • Hey there. I haven't tried that. The mapping is happening correctly [as per the docs](http://documentcloud.github.com/backbone/#Router). I'm just curious as to why those duplicate functions are being called. When I call the router.navigate directly, however, that solves the problem. But I'm still trying to find out how to deal with browser bar and forward and back button. – Nutritioustim Nov 26 '11 at 20:29

2 Answers2

1

I got this cleared up by another SO question. I didn't realise that I had to use the router.navigate function strictly.

Using the router programmatically (not via browser bar), those duplicate calls go away. I'm also seeing the expected functions called only once... when using router.navigate.

I still have to find out how to capture back & forward buttons to call those functions. Thanks for the feedback so far.

Community
  • 1
  • 1
Nutritioustim
  • 2,686
  • 4
  • 32
  • 57
0

Try /accounts$ instead. $ is the regex for the end of the string.

Justin Thomas
  • 5,680
  • 3
  • 38
  • 63
  • I actually tried _/accounts$_ in the routes hash. But to no avail. It works if I use the raw router function _router.route(route, name, callback)_ . It's weird, because again, all the routes are getting called. I'm just getting duplicate calls when I go to _/accounts_ , _/accounts/account/123_ , etc. – Nutritioustim Nov 26 '11 at 18:55