Skip to content

Instantly share code, notes, and snippets.

@lexeek
Created November 8, 2021 15:56
Show Gist options
  • Save lexeek/a4ff4bea6ec5fbce670f07cd68c8a51b to your computer and use it in GitHub Desktop.
Save lexeek/a4ff4bea6ec5fbce670f07cd68c8a51b to your computer and use it in GitHub Desktop.
import {BaseEventEmitter} from './base.event.emitter'
import {RESIZE_EVENT_NAME, ResizeEventEmitter} from "./resize.event.emitter";
import {fromEvent, Subscription} from "rxjs";
export const CHANGE_OFFSET_SIZE = 'change:offset:size';
export interface ChangeOffsetSizeData {
element: HTMLElement;
newOffsetWidth: number;
newOffsetHeight: number;
isOffsetWidthChanged: boolean;
isOffsetHeightChanged: boolean;
}
export class ChangeOffsetSizeEventEmitter extends BaseEventEmitter {
oldOffsetWidth: number;
oldOffsetHeight: number;
private observer: MutationObserver;
private resizeEventEmitter: ResizeEventEmitter;
private subscription: Subscription = new Subscription();
onInit(): void {
this.oldOffsetWidth = this.element.offsetWidth;
this.oldOffsetHeight = this.element.offsetHeight;
this.observer = new MutationObserver(this.onChanges.bind(this));
const config = {
childList: true,
attributes: true,
characterData: true,
subtree: true
};
this.observer.observe(this.element, config);
this.resizeEventEmitter = new ResizeEventEmitter(this.element);
this.subscription = new Subscription();
this.subscription.add(fromEvent(this.element, RESIZE_EVENT_NAME).subscribe(this.onChanges.bind(this)));
}
private onChanges(): void {
const newOffsetWidth = this.element.offsetWidth;
const newOffsetHeight = this.element.offsetHeight;
console.log('newOffsetWidth', newOffsetWidth);
console.log('newOffsetHeight', newOffsetHeight);
const isOffsetWidthChanged = (newOffsetWidth !== this.oldOffsetWidth);
const isOffsetHeightChanged = (newOffsetHeight !== this.oldOffsetHeight);
this.oldOffsetWidth = newOffsetWidth;
this.oldOffsetHeight = newOffsetHeight;
const isResize = (isOffsetWidthChanged || isOffsetHeightChanged);
if (isResize) {
const detail: ChangeOffsetSizeData = {
element: this.element,
newOffsetWidth,
newOffsetHeight,
isOffsetWidthChanged,
isOffsetHeightChanged
};
const event = new CustomEvent(this.getEventName(), {detail});
this.element.dispatchEvent(event);
}
}
onDestroy(): void {
this.observer && this.observer.disconnect();
this.resizeEventEmitter && this.resizeEventEmitter.destroy();
this.subscription && this.subscription.unsubscribe();
}
getEventName(): string {
return CHANGE_OFFSET_SIZE;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment