Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

javascript - Backbone.js detecting scroll event

I have a following view

var FullWindow = Backbone.View.extend({
  initialize: function() {
    _.bindAll(this, 'detect_scroll');
  },

  // bind the events
  events : {
    "scroll" : "detect_scroll"
  },

  detect_scroll: function() {
    console.log('detected');
  }
});

and I initialize it via

var full_window = new FullWindow({el:$('body')});

But I don't think it's working.

When I change the events to

events : {
  "click" : "detect_scroll"
},

It's fine.

What's wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...