admin管理员组

文章数量:1415467

I'm trying to do a route with backbone.js that match '/object/:id'

Problem is, i can receive get parameters containing anything, including slashes, then backbone doesn't recognize this url : /object/1337?var=/hey

Can i ignore get parameters or simply say that i want my route to begin with '/object/:id?' ?

Thanks.

I'm trying to do a route with backbone.js that match '/object/:id'

Problem is, i can receive get parameters containing anything, including slashes, then backbone doesn't recognize this url : /object/1337?var=/hey

Can i ignore get parameters or simply say that i want my route to begin with '/object/:id?' ?

Thanks.

Share Improve this question edited Jun 20, 2017 at 11:10 laser 1,37613 silver badges14 bronze badges asked Jan 6, 2012 at 14:14 IntrepiddIntrepidd 21k7 gold badges59 silver badges63 bronze badges 1
  • Can you URL encode the parameter? – Marcus Adams Commented Jan 6, 2012 at 14:45
Add a ment  | 

4 Answers 4

Reset to default 4

Finally found a solution, maybe a little ugly

initialize : function() {
  this.route(/^object\/([^\?]*)\?/, "show", this.show);
}

I believe this would work for you:

'/object/:id/*splat'

Your 'id' parameter will still match your id and the 'splat' on the end will match anything that is appended at the end. It will even match nothing. So if you want to trigger this route without any get parameters then '/object/1337/' will work. Notice the slash at the end. It has to be there.

Your original link of /object/1337?var=/hey should also trigger this route.

EDIT: You can read about splats at

http://documentcloud.github./backbone/#Router-routes

EDIT EDIT: Your original link will work with the new slash in between your id and the '?'

/object/1337/?var=/hey

I use following for this:

// Call for Backbone to make the route regexp
var route = Backbone.Router._routeToRegExp(route_string);
// Change the regexp to ignore GET parameters
route = new RegExp(route.source.replace(/\$/, "\\\/?(?:(\\\?.*$))*$");
// Create a route with a new regexp
// Backbone will not try to make a regexp from the route argument if it's already a RegExp object
this.route(route, name, callback);

If all you want is to separate parameters from the fragment, I suggest using backbone-query-params.

You can use mon Backbone routes and the plugin will parse the GET parameters in an object that is then passed to the route handler function.

From the plugin's Github page:

routes: {
    'object/:id': 'myRoute'
}
...
myRoute: function(id, params) {

    // if the routed url is '/object/1337?var=/hey'
    console.log( id );     // ---> '1337'
    console.log( param );  // ---> { var : '/hey' }

}

本文标签: