Simple Backbone search page - how would you do it?

泄露秘密 提交于 2019-12-03 09:47:24

问题


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.


回答1:


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);
   }
});


来源:https://stackoverflow.com/questions/10671435/simple-backbone-search-page-how-would-you-do-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!