Skip to content

Instantly share code, notes, and snippets.

@mxriverlynn
Created December 15, 2011 14:14
Show Gist options
  • Save mxriverlynn/1481224 to your computer and use it in GitHub Desktop.
Save mxriverlynn/1481224 to your computer and use it in GitHub Desktop.
search with backbone collections
var results = new SearchResults();
results.searchTerm = "some search term";
results.fetch({
success: someView.showTheResults
});
// handle the search results in a view
Backbone.View.extend({
initialize: function(){
MyApp.vent.bind("search:results", this.showResults, this);
},
showResults: function(results){
this.collection = results;
this.render();
},
render: function(){
var html = $("#some-template").tmpl(this.collection.toJSON());
$(this.el).html(html);
}
});
// do the actual search, based on a search
// term that was entered in to the search box
SearchResults.search("some search term");
SearchResults = Backbone.Collection.extend({
url: function(){
return "/items/" + this.searchTerm;
}
}, {
search: function(searchTerm){
var results = new SearchResults();
results.searchTerm = "some search term";
results.fetch({
success: function(){
MyApp.vent.trigger("search:results", results);
},
error: function(collection, response){
MyApp.vent.trigger("search:error", response);
}
});
}
});
SearchResults = Backbone.Collection.extend({
url: function(){
return "/items/" + this.searchTerm;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment