Backbone.js detecting scroll event
I don't think that the body
element will fire a scroll event unless you explicitly give it a scrollbar by setting set its overflow
property to scroll
in CSS. From the jQuery docs:
The scroll event is sent to an element when the user scrolls to a different place in the element. It applies to window objects, but also to scrollable frames and elements with the overflow CSS property set to scroll (or auto when the element's explicit height or width is less than the height or width of its contents).
Assuming that you aren't explicitly giving the body
element a scrollbar with overflow:scroll
and/or a fixed height, the scroll
event you want to listen for is probably being fired by the window
object, not the body
.
I think the best approach here is to drop the Backbone event binding (which is really just a shorthand, and only works on events within the view.el
element) and bind directly to the window in initialize()
:
initialize: function() {
_.bindAll(this, 'detect_scroll');
// bind to window
$(window).scroll(this.detect_scroll);
}
I think the problem is that Backbone uses event delegation to capture events, that is it attaches listeners to the this.$el
, and that the scroll
event does not bubble up by definition.
So, if the scroll
event occurs for a child (or descendant) of this.$el
, then this event can not be observed at this.$el
.
The reason it works for click
, is just because click
bubbles up.