In my Backbone application I have a main view that shows previews of posts. When the user clicks on a post, the post is expanded in an overlay and the URL is changed to reflect that post. While the post is expanded the user may do something that triggers a call to the server that needs to happen at the root context. The problem is that when the post is expanded, the server call that needs to happen at the root context happens from the post context instead. Here’s the order of operations:
- Page is loaded with main view url: http://localhost:8080/my-web-app/
- User clicks post, overlay is shown, url updated to: http://localhost:8080/my-web-app/posts/1
- User clicks something that triggers a call to server. Url is: http://localhost:8080/my-web-app/posts/1/load, which is wrong.
In the example above, the load operation needs to happen from the root context: http://localhost:8080/my-web-app/load
I’ve tried changing the url property for my models, collections, etc. to include a leading /, but this removes the “/my-web-app/” context (the url becomes http://localhost:8080/load), which is necessary in my test environment. This would work fine in a production environment, of course.
To get around this, I have set the Backbone.history root option to be “/my-web-app/” and have overridden every url property to be as follows:
url: function() {
(Backbone.history.options.root != undefined ? Backbone.history.options.root : "") + "load";
}
While this approach works, it is a pain in the ass to override every url function like this… not to mention, it feels hacky. It is also totally unecessary code for a production environment. Is there a more elegant way to manage this so that it works in both test and production environments?
Thanks!
Application routing shouldn’t differ on dev environment and production. This will always bring trouble at some point.
Assuming you’re using Apache server on your localhost, you can make a virtual host of your choice and make
/my-web-app/available on the/.First, add a domain name to your /etc/hosts file and point it to 127.0.0.1, like that:
and then add a virtual host to your Apache
vhosts.confAnd you’re done! Your webapp is available on //mywebapphost:8080 and all routing is identical to your production environment.