Question

I'm working on a website where we are using 3rd Party web services to return dynamic content and using javascript to parse and display that data from to the page. We are already using backbone in a couple places on the site to post data to web services so I had the thought of trying to use Backbone's router to run specific functions based on the page url and grabbing the query because we are hashing the queries to the url of the page.

For example: global-site-search.html#query

This is the router code I have to this point:

var Router = Backbone.Router.extend({
    routes : {
        '' : 'indexRoute',
        'global-site-search.html(:query)' : 'getSearchResults'
    },

    indexRoute: function(query) {
        console.log("indexRoute");
    },

    getSearchResults: function(query) {
        console.log("getSearchResults with query", query);
    }
});

var WaRouter = new Router();

Backbone.history.start({
    pushState: true,
    root: '/'
});

But when I hit the page with a url like global-site-search.html#query the query value returns null. Has anyone tried this before or am I trying to extend Backbone's router to far in handling this?

Was it helpful?

Solution

Is global-site-search.html from your server?, if yes then the config for router should be

':query' : 'getSearchResults'

If no, then you can't do that, because Backbone.Router uses the hash part of the current page URL to track pages. And since global-site-search.html is not containing any backbone code, it can't do anything. It is possible only if you somehow can inject your router code into global-site-search.html which is illegal in this case

Updated: this should allow you to search with this route ':query' : 'getSearchResults'

Backbone.history.start({
    pushState: true,
    root: window.location.pathname
});

When using router, you need to set the correct root, so using window.location.pathname is the easiest way to do that. Also, according to Backbone documentation

and if a hash URL is visited by a pushState-capable browser, it will be transparently upgraded to the true URL. Note that using real URLs requires your web server to be able to correctly render those pages, so back-end changes are required as well. For example, if you have a route of /documents/100`

Since you are not having any real back-end to handle pushState, I suggest that you turn it off

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top