I'd like to implement a search page using Backbone.js
. The search parameters are taken from a simple form, and the server knows to parse the query parameters and return a json array of the results. My model looks like this, more or less:
App.Models.SearchResult = Backbone.Model.extend({
urlRoot: '/search'
});
App.Collections.SearchResults = Backbone.Collection.extend({
model: App.Models.SearchResult
});
var results = new App.Collections.SearchResults();
I'd like that every time I perform results.fetch()
, the contents of the search form will also be serialized with the GET
request. Is there a simple way to add this, or am I doing it the wrong way and should probably be handcoding the request and creating the collection from the returned results:
$.getJSON('/search', { /* search params */ }, function(resp){
// resp is a list of JSON data [ { id: .., name: .. }, { id: .., name: .. }, .... ]
var results = new App.Collections.SearchResults(resp);
// update views, etc.
});
Thoughts?
Found a very simple solution - override the
url()
function in the collection:Hopefully this doesn't horrify anyone who has a bit more Backbone / Javascript skills than myself.
Attention: code simplified and not tested
I think you should split the functionality:
The Search Model
It is a proper resource in your server side. The only action allowed is
CREATE
.The Results Collection
It is just in charge of collecting the list of Result models
The Search Form
You see that this View is making the intelligent job, listening to the
form.submit
, creating a newSearch
object and sending it to the server to becreated
. Thiscreated
mission doesn't mean the Search has to be stored in database, this is the normalcreation
behavior, but it does not always need to be this way. In our casecreate
a Search means to search the DB looking for the concrete registers.I think this kind of solution is very clean, elegant, intuitive and very extensible.
Backbone.js fetch with parameters answers most of your questions, but I put some here as well.
Add the
data
parameter to yourfetch
call, example:Now your call url has added parameters which you can parse on the server side.
It seems the current version of Backbone (or maybe jQuery) automatically stringifies the
data
value, so there is no need to call$.param
anymore.The following lines produce the same result:
The querystring will be
filter=abc&page=1
.EDIT: This should have been a comment, rather than answer.