Skip to content

Instantly share code, notes, and snippets.

@gabemeola
Created January 5, 2018 18:02
Show Gist options
  • Save gabemeola/428e193c2200011576aa2a886d187c3f to your computer and use it in GitHub Desktop.
Save gabemeola/428e193c2200011576aa2a886d187c3f to your computer and use it in GitHub Desktop.
import { debounce } from 'lodash';
class ResizeObservable {
constructor() {
this.listeners = [];
this._resizeFunc = debounce(() => {
this.emit();
}, 300);
}
subscribe(func) {
if (this.listeners.length === 0) {
window.addEventListener('resize', this._resizeFunc);
}
this.listeners.push(func);
return {
unsubscribe: () => {
this.listeners = this.listeners.filter((f) => f !== func);
if (this.listeners.length === 0) {
window.removeEventListener('resize', this._resizeFunc);
}
},
};
}
emit(message) {
if (this.listeners.length === 0) return;
// console.log('listeners', this.listeners);
for (let i = 0; i < this.listeners.length; i++) {
this.listeners[i](message);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment