Reputation: 9262
This is my routes object in a BackboneJS app:
routes: {
"" : "_navigate",
"home" : "_navigate",
"blog" : "_navigate",
"photos" : "_navigate",
"notes" : "_navigate",
"about" : "_navigate",
"singlepost_:id" : "_navigate"
},
it redirects routes to the _navigate
method, which looks like this:
_navigate: function(postId) {
if (postId) {
// show single entry
return;
}
// show regular entry
},
It works perfectly fine. However, I find the repetitive routes object to be annoying.
My question is: Is there a better way to direct all these routes to the same method without repeating yourself so much?
Thanks!
Upvotes: 2
Views: 669
Reputation: 11435
http://backbonetutorials.com/what-is-a-router/ Check out the section on splats
Any "*splats" or ":params" in route definitions are passed as arguments (in respective order) to the associated function. A route defined as "/:route/:action" will pass 2 variables (“route” and “action”) to the callback function. (If this is confusing please post a comment and I will try articulate it better) Here are some examples of using ":params" and "*splats"
routes: {
"/posts/:id": "getPost",
// <a href="http://example.com/#/posts/121">Example</a>
"/download/*path": "downloadFile",
// <a href="http://example.com/#/download/user/images/hey.gif">Download</a>
"/:route/:action": "loadView",
// <a href="http://example.com/#/dashboard/graph">Load Route/Action View</a>
},
getPost: function( id ){
alert(id); // 121
},
downloadFile: function( path ){
alert(path); // user/images/hey.gif
},
loadView: function( route, action ){
alert(route + "_" + action); // dashboard_graph
}
Upvotes: 2
Reputation: 9262
Quite simple, really.
routes: {
"*actions:_id": "_navigate"
}
Thanks to Jason Strimpel from the BackboneJS Google Group.
Upvotes: 1