如何在课内使用IntersectionObserver?
在类中使用InterSectionObserver遇到问题。例如,我是从类构造仪观察者实例创建的,并在当前类中创建回调函数。当函数执行“此”不指向我的类实例时,它指向观察者实例。我尝试使用箭头功能和其他方式,但没有任何结果。有什么想法吗?
class SomeClass {
constructor(className) {
this.className = className;
this.element = document.getElementByID(this.className);
this.observer = new IntersectionObserver(this.someFunc, {threshold: 0.5});
this.observer.observe(this.element);
}
someFunc(entry) {
entry.forEach((change) => {
console.log(this.className);
});
}
}
someInstance = new SomeClass("some-class__element");
Encountered a problem with using IntersectionObserver inside a class. For example, I am creating from my class constructor observer instance and create a callback - function in the current class. When the function executes "this" not points to my class instance, it points to Observer instance. I tried to use arrow functions and other ways, but didn't any results. Any ideas?
class SomeClass {
constructor(className) {
this.className = className;
this.element = document.getElementByID(this.className);
this.observer = new IntersectionObserver(this.someFunc, {threshold: 0.5});
this.observer.observe(this.element);
}
someFunc(entry) {
entry.forEach((change) => {
console.log(this.className);
});
}
}
someInstance = new SomeClass("some-class__element");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我找不到更好的解决方案(或正确的方法),但是我做了下一件事。由于IntersectionObserver是异步的,因此我无法通过“此”访问我的班级访问。因此,我只是通过InterSectionObserverentry创建了我类的观察者回调函数实例。在父元素内部,我最初将其放置在我的“某个类别__Element”脚本附近,其中创建了此类实例。我可以实例并将其用于我的目的。
ps,如果不是PHP自动生成的类实例变量,则会更容易
I didn't find a better solution (or right way), but I made next thing. Because IntersectionObserver is asynchronous, then I can't get by "this" access to my class. So, I just create an observer callback function instance of my class by IntersectionObserverEntry. Inside parent element, I initially putted near my "some-class__element" Script where create instances of this class. I get to instance and use this for my purposes.
P.S. It would be easier if the class instance variable was not automatically generated by PHP