Created
January 5, 2018 18:02
-
-
Save gabemeola/428e193c2200011576aa2a886d187c3f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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