javascript - Backbone.js 检测滚动事件

标签 javascript backbone.js

我有以下观点

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

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

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

我通过初始化它

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

但我认为这不起作用。

当我将事件更改为

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

没关系。

出了什么问题?

最佳答案

我认为 body 元素不会触发滚动事件,除非您通过将其 overflow 属性设置为 scroll< 来显式为其提供滚动条 在 CSS 中。来自 jQuery 文档:

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).

假设您没有明确为 body 元素提供带有 overflow:scroll 和/或固定高度的滚动条,则 scroll您想要监听的事件可能是由 window 对象触发的,而不是 body

我认为最好的方法是删除 Backbone 事件绑定(bind)(这实际上只是一种简写,仅适用于 view.el 元素内的事件)并直接绑定(bind)到窗口初始化():

initialize: function() {
    _.bindAll(this, 'detect_scroll');
    // bind to window
    $(window).scroll(this.detect_scroll);
}

关于javascript - Backbone.js 检测滚动事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7634529/

相关文章:

JavaScript 正则表达式 : find non-numeric character

javascript - 如何从 Backbone 路由器中提取 id 参数

javascript - 如何在 Marionette ItemView 中更新的集合中的对象上运行 toJSON?

javascript - 如何使用主干 Js 从 ListView 编辑记录

javascript - 容器高度增加后控制 border-radius

javascript - 从react-icons组件获取SVG

javascript - 无法从 JavaScript 访问 CSS 某些样式字段

javascript - backbone.js - model.save() 生成错误的 PUT url 路径

javascript - 将事件绑定(bind)到下划线/主干中的动态对象

json - underscore.js - 对象不支持此属性或方法 - ie8