There are a few issues here:
- A fetch should be a GET, not a POST, because a fetch should not save or modify anything
- Maybe just a personal preference, but I'd
url
as a function, so as to avoid trying to modify the AJAX request options manually. - The
fetch
call will always be asynchronous, so you need to either add asuccess
callback in the options hash, or add a listener to the collection'sreset
event
I'd write the collection like this:
ES.Results = Backbone.Collection.extend({
initialize: function() {
this.query = "test";
},
model: ES.Result,
url: function() {
return '/search/query?query=' + this.query;
}
});
Then set the search when you create the collection:
var resultsData = new ES.Results();
resultsData.query = "soccer";
And use success
and/or the on("reset")
event to handle the result:
resultsData.on("reset", function(collection) {
console.log(collection);
});
console.log("Fetching....");
resultsData.fetch({
success: function(collection, response) {
console.log("Got data!" + collection.length);
},
error: function(collection, response) {
console.log("Error: " + response.responseText);
}
});