1

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");
D. Popov
  • 21
  • 5
  • 1
    Should not the `getElementByID` be `getElementById`? – Tanay Apr 17 '22 at 08:48
  • I retyped new example, here I accidentally left a typo in the code, howeverthere. Element is already in a class, but I can’t get access from observer callback – D. Popov Apr 17 '22 at 10:15
  • `getElementById` takes an id, not a classname… and you could access that via `change.target.id` even without access to your instance – Bergi Apr 17 '22 at 12:55
  • ```@Bergi``` You're right, but I retyped example, and get typo this too :-) But ```change.target.id``` won't give me access to instance of SomeClass. In my real work I need to get access to another properties of SomeClass – D. Popov Apr 17 '22 at 14:08

1 Answers1

-1

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.

someFunc(entry) {
  entry.forEach((change) => {
    var classInstance = change.target.parentElement.lastElementChild.innerText.split(" ", 1)[0];
    var self = window[classInstance];
    console.log(self.className);
  });
}

P.S. It would be easier if the class instance variable was not automatically generated by PHP

<div class="some-class">
  <p id="some-class__element">0</p>
  <script>Vdfa5c592c147398f80e37058331ae17e = new SomeClass("some-class__element");</script>
</div>
D. Popov
  • 21
  • 5