gpt4 book ai didi

javascript - Ember JS 中的滚动检测?

转载 作者:行者123 更新时间:2023-12-03 22:25:18 25 4
gpt4 key购买 nike

在 Ember JS 中检测滚动的最佳方法是什么?没有内置的滚动 Action ,我可以使用 jquery 但不知道放在哪里?它会因为它具有应用程序范围而进入我的 application.js 还是其他地方?

实际的滚动检测/逻辑在这里不是问题,而是如何以 Embery 方式设置这样的脚本。

理想情况下,滚动是一个 Action ,可以在 application.js 文件中处理:

import Ember from 'ember';

export default Ember.Route.extend({
actions: {
onScroll: function() {
alert('scrolled');
}
}
});

最佳答案

在工作中,我们使用生命周期 Hook 来注册/取消注册未在 Ember 中实现的事件。我们使用 didInsertElementwillDestroyElement 生命周期 Hook 将 jQuery 事件绑定(bind)/取消绑定(bind)到特定命名空间(通常是组件 ID):https://guides.emberjs.com/v2.8.0/components/the-component-lifecycle/

代码示例:

import Ember from 'ember';

export default Ember.Component.extend({

didInsertElement() {
this._super(...arguments)

// Register your events here
Ember.$(document).on('scroll.my-namespace', 'body', this.eventHandler)
// this.$ if the element is located inside the component
},

willDestroyElement() {
this._super(...arguments)

Ember.$(document).off('scroll.my-namespace')
// this.$ if the element is located inside the component
},

eventHandler(ev) {
//Do sth with event
}

})

另一种方法是扩展 Ember.Evented 的服务。在该服务中,您还可以注册一个 jQuery 事件监听器。需要监听滚动事件的组件可以订阅服务(http://emberjs.com/api/classes/Ember.Evented.html)。

关于javascript - Ember JS 中的滚动检测?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39596474/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com