Capture scroll event on div

David Sulc picture David Sulc · Apr 21, 2012 · Viewed 14.2k times · Source

I'm trying to capture the scroll event within a Backbone.Marionette.CompositeView, but without success.

As an exercise, I'm rewriting http://www.atinux.fr/backbone-books/ using Backbone.Marionette. As you can see, when you scroll down, more books are fetched and displayed (i.e. infinite scroll). However, I'm unable to capture the scroll event on my view.

Here's my (simplified) code:

  LibraryView = Backbone.Marionette.CompositeView.extend({
    // properties, initializer, etc.

    events: {
      'scroll': 'loadMoreBooks',
      'click': 'loadMoreBooks'
    },

    // some functions

    loadMoreBooks: function(){
      console.log("loadMoreBooks");
    }
  });

The full source code can be seen here: https://github.com/davidsulc/backbone.marionette-atinux-books/blob/scroll/assets/javascript/app.js#L86-89

What I don't understand is that the "click" event is being triggered properly, but the "scroll" event isn't. What am I doing wrong?


Edit: so the error was pretty simple in the end... I was passing "el: #content" to the view's contructor, but the scroll was defined in CSS on ".library". So once I changed my DOM from

<div id="content">
  <div class="library">
  </div>
</div>

to

<div id="content" class="library"></div>

everything worked properly...

Answer

Chris Smith picture Chris Smith · Nov 27, 2012

Backbone attaches to the top el element to look for all events. Some DOM events are not bubbled to parent elements and this includes scroll. The click event worked because it does bubble.

Ref: http://www.w3.org/TR/2009/WD-DOM-Level-3-Events-20090908/#event-type-scroll