Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Backbone search page - how would you do it?

I'm want to implement a simple search page using Backbone. It is not a single page application, but still would like to structure my JavaScript code using Backbone. A search page consists of a search form and search results. The search is done via AJAX and has to be saved in history. When the page is loaded from history, search query parameters should be loaded into the form. The search form and the search results can be implemented as Backbone.View's. However, I have problems glueing them together.

What I think I need i some sort of controller. There is a Backbone.Router, but is it the right place? Where should the AJAX call be placed?

Any advice on the structure of such page is welcomed.

like image 808
Infeligo Avatar asked May 20 '12 06:05

Infeligo


1 Answers

You can create a SearchModel. The SearchModel would have a method like: "performSearch(string)" that would fire off your ajax call. When the call returns the model could do something like:

this.set("searchResults", ajaxResult)

and your views can bind to that property of the model:

// SearchResultsView
Backbone.View.extend({
    initialize: function() {
        this.model.on("change:searchResults", this.displayResults, this);
    },
    displayResults: function(model, results) {
        // do whatever...
    }
});

example search form view for reference:

Backbone.View.extend({
   events: {
      "submit": "formSubmitted"
   },
   formSubmitted: function(e) {
      this.model.performSearch(e.target.value);
   }
});

example SearchModel for reference:

Backbone.Model.extend({
   performSearch: function(string) {
      // fire your ajax request.  provide a bound
      // _searchComplete as the callback
   },
   _searchComplete: function(results) {
     this.set("searchResults", results);
   }
});
like image 150
Matt Wonlaw Avatar answered Sep 19 '22 19:09

Matt Wonlaw