passing url as hashmaps in backbone route?
-
18-06-2021 - |
Question
I'm trying to pass a directory location and the file path as part of the hashmaps in backbone routes. This is the url with hashmaps:
localhost/index.html#directory-http://localhost/foobar-html/foo.html
and this is what my route that maps the above url:
routes: {
'directory-*directoryPath-*filePath': 'render'
},
render: function (directoryPath, filePath) {
// I get the entire url in directoryPath variable
// http://localhost/foobar-html/foo.html
// and filePath is empty.
}
What would be the right way to map such type of hash URL? Thanks!
Solution
From the fine manual:
Routes can contain parameter parts,
:param
, which match a single URL component between slashes; and splat parts*splat
, which can match any number of URL components.
Your problem is that a splat eats up everything so having two splats in one route is pointless; you can't use a parameter part, :x
, because that stops at a slash.
There are a few things you can do.
You could URI encode the slashes in link and use parameter parts. The URL would look like this:
#directory-http:%2f%2flocalhost%2ffoobar-html%2ffoo.html
and the router would be like this:
routes: { 'directory-:directoryPath-:filePath': 'render' }, render: function(d, f) { d = decodeURIComponent(d); f = decodeURIComponent(f); //... }
You could add your route as a regex using
route
, that would give you more freedom in how you construct the pattern. For example, a fragment like this:#directory-http://localhost/foobar-html/foo.html
could be handled with a router like this:
initialize: function() { this.route(/directory-(.*?)-(.*)/, 'render'); }, render: function(d, f) { //... }
The second option will run into problems with you inevitably get a -
inside your directoryPath
or filePath
; you could URI encode embedded -
s to get them through the first option though.