Simple Backbone search page - how would you do it?

前端 未结 1 1255
闹比i
闹比i 2021-02-04 15:50

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 pa

相关标签:
1条回答
  • 2021-02-04 16:26

    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);
       }
    });
    
    0 讨论(0)
提交回复
热议问题