Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should Backbone.js grab GET parameters from URL?

I am trying to implement a search function for my website. When the user types a search term foobar into a input box and submits it, he is redirected to http://mydomain.com/search?query=foobar.

Problem:: How should I grab the GET parameters query from the URL, and send it to the backend and get a array of results back as a JSON response? Should I even do it this way?

My current attempt below does not even cause the search function to be triggered.

Router

var AppRouter = Backbone.Router.extend({
    routes: {
        'search?query=:query': 'search'
        // ... and some other routes
    },

    search: function(query) {
        this.photoList = new SearchCollection();
        var self = this;
        this.photoList.fetch({
            data: {query: query},
            success: function() {
                self.photoListView = new PhotoListView({ collection: self.photoList });
                self.photoListView.render();
            }
        });
    }

});

var app = new AppRouter();
Backbone.history.start({
    pushState: true,
    root: '/'
});
like image 995
Nyxynyx Avatar asked Aug 07 '12 01:08

Nyxynyx


2 Answers

There have been several issues filed against Backbone for this very issue. There is an existing plugin that works well for this:

https://github.com/jhudson8/backbone-query-parameters

Alternatively, I'm currently using query string parameters in a mock API that matches Backbone's route matching. Looks something like this

Route

"/api/v2/application/:query"

Query

application: function(query) {
  var params = $.deparam(query.slice(1));
  // params.something...
}

As to your actual issue at hand how are you redirecting to index.html to support pushState?

like image 171
tbranyen Avatar answered Oct 22 '22 09:10

tbranyen


I hit this same issue and contemplated using backbone-query-parameters, but that should be considered generally an incorrect approach.

The url query string is not meant for the front end. They get sent to the server and force a refresh when navigating from page.html to page.html?something=something.

You should be using hash fragments instead. i.e. http://www.example.com/ajax.html#key1=value1&key2=value2 then just get those values the normal backbone way and build your request params from that.

See https://github.com/jashkenas/backbone/issues/891, https://developers.google.com/webmasters/ajax-crawling/docs/specification, https://www.rfc-editor.org/rfc/rfc3986#section-3.5

like image 27
Gerard Avatar answered Oct 22 '22 10:10

Gerard