Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone routing regex

Tags:

backbone.js

Trying to get my head around sorting this routing regex out, so:

'quotes(/:action)': 'quotes',
'quotes/:id(/:params)': 'quotesEdit'

Two URLs:

http://domain.com/#quotes/action=showModal
http://domain.com/#quotes/123

My question:

How can I make sure that the URL with the action= matches on the first Route, but not the second? and for urls like quotes/123 to fall through to the second Route?

like image 469
benhowdle89 Avatar asked Aug 05 '13 15:08

benhowdle89


2 Answers

You can make this work by over-riding Backbone.history.loadUrl with your special-cases. Essentially, you would be skipping matched routes based on the url parameters...but that seems awfully hack-ish.

An option is to declare a single route and branch on the arguments:

'quotes(/:id)(/:params)': 'quotes'

quotes:function(id,params) {
  if (id && id.match(/^\d+$/)) { // if id is a number
    this.quotesEdit(id,params);
  }
  else {
    // your quotes logic
  }

Instead of the above, you may want to look into changing your routes a bit and your problem is longer an issue.

'quotes(/:action)'          : 'quotes',
'quotes/edit/:id(/:params)' : 'quotesEdit'
like image 42
fbynite Avatar answered Nov 09 '22 08:11

fbynite


try to add routes directly via router`s initialize

    initialize: function(options) {
        this.route(/^quotes\/([0-9]+)$/, "ids");
        this.route(/^quotes\/action=(.*)$/, "act");
    },
    ids: function(id){
        alert('id='+id);
    },
    act: function(act){
        alert('act='+act);
    },
like image 66
shukshin.ivan Avatar answered Nov 09 '22 09:11

shukshin.ivan