Should Backbone.js grab GET parameters from URL?
Solution 1
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
?
Solution 2
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
Nyxynyx
Hello :) I have no formal education in programming :( And I need your help! :D These days its web development: Node.js Meteor.js Python PHP Laravel Javascript / jQuery d3.js MySQL PostgreSQL MongoDB PostGIS
Updated on June 19, 2022Comments
-
Nyxynyx almost 2 years
I am trying to implement a search function for my website. When the user types a search term
foobar
into ainput
box and submits it, he is redirected tohttp://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: '/' });