jqueryunderscore.jsbackbone-viewsbackbone-events

Backbone JS scroll event handling


I am trying to implement scroll event in backbone JS using JQuery and underscore. in initialize function I add below lines :

 _.bindAll(this, 'filter_list');
 $(window).scroll(this.filter_list);

where filter_list is function from where I am trying to fetch data for next 50 entries in DB.

For the first time, the page display 100 records from DB. On the scroll hit bottom of page, the filter_list function gets called which has logic to fetch next 50 entries from DB.

The scroll event hits when scroll bar is at the bottom of page however instead of call filter_list once, the scroll event is called multiple times, which ends up fetching same data from DB multiple times. Add the same results get updated to the page, i.e. same 50 records displayed multiple time.

I tried registering event in different ways but of no use. Also if anyone can explain the scroll event and binding mechanism in backbone JS then it would be great, I didn't get any good stuff on internet.

Thanks in advance


Solution

  • The scroll event is fired every time the scroll bar moves, you need to do all the fetching logic yourself. Here is an idea:

    var MyView = Backbone.View.extend({
      initialize: function() {
        _.bindAll(this, 'filter_list');
        // also good idea to debounce
        this.filter_list = _.debounce(this.filter_list, 300);
        // Keep internal fetching state
        this.isFetching = false;
        $(window).scroll(this.filter_list);  
      },
    
      filter_list: function() {
        if (this.scrollHitPageBottom() && !this.isFetching) {
          this.isFetching = true;
          this.fetchDBEntries()
              .finally(function() { this.isFetching = false });
        }
      },
    
      ... 
    })