ResizeObserver callback is not being fired when rotated device two times

27 Views Asked by At

I am using ResizeObserver Api to listen to orientation change and fullscreen mode change. The observer is getting registered successfully. When moved from portrait mode to landscape mode, the callback is being fired. But for subsequent change from landscape to portrait and vice-versa, callback is not executed. I can confirm that observer instance is still alive, as for full-screen mode change, screen resize event is being listened successfully.

expected behavior: When created instance of ResizeObserver API, it should listen to all resize, orientation change, full-screen mode change events.

noticed bahavior: Orientation change event is captured only once. After that it's not listening to the event. At same time listening to other resize events.

Implementation:



type TCallback = {
  [key in string]: (_:ResizeObserverEntry)=>void
}

export class ContainerObserver  {
  private static instanceCache: ContainerObserver ;

  private observerInstance: ResizeObserver;

  private resizeCallbacks: {
    [key in string]: (_: ResizeObserverEntry) => void;
  } = {};

  private RootContainer: HTMLDivElement;

  private constructor() {
    this.RootContainer = document.querySelector("#root")!;
    if (this.RootContainer) {
      this.observerInstance = new ResizeObserver((entries) => {
        const relativeTo = entries?.[0];
        Object.values(this.resizeCallbacks).forEach((callback) => {
          callback(relativeTo);
        });
      });
      
      this.observerInstance.observe(this.RootContainer);
    }
  }

  public static get instance(): ContainerObserver  {
    if (!ContainerObserver .instanceCache) {
      ContainerObserver .instanceCache = new ContainerObserver ();
    }

    return ContainerObserver .instanceCache;
  }
  
  addCallbackObserver(callback:TCallback)  {
    
    this.resizeCallbacks   =  {
      ...this.resizeCallbacks,
      ...callback
    } ;

    console.log({callbacks: this.resizeCallbacks})
    
  }
  getInstance(){
    return this.observerInstance
  }

  // Method to stop observing an element
  unobserve() {
    this.observerInstance.unobserve(this.RootContainer);
  }
}

usage of the class:

ContainerObserver.instance.addCallbackObserver({ handleResize });
0

There are 0 best solutions below