Simple Backbone search page - how would you do it?

人走茶凉 提交于 2019-12-03 00:16:32
Matt Crinklaw-Vogt

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