JCHappytime / TC-Music

写着玩
0 stars 0 forks source link

设置响应式:window监听resize变化 #98

Open JCHappytime opened 3 years ago

JCHappytime commented 3 years ago

import _ from 'lodash';

let RS; class Responsive { state = null;

listeners = null;

resizeListeners = null;

size = { width: null, height: null, state: null, };

constructor() { this.listeners = []; this.resizeListeners = []; if (window) { window.addEventListener('resize', () => { this.resized(); }); this.size.width = window.innerWidth; this.size.height = window.innerHeight; this.state = this.checkState(); this.size.state = this.state; } }

resized() { this.size.width = window.innerWidth; this.size.height = window.innerHeight; const s = this.checkState(); this.resizeListeners.forEach(fn => fn(this.size)); if (s === this.state) return; this.state = s; this.size.state = s; this.listeners.forEach(fn => fn(s)); }

checkState() { const wh = this.size.width; if (wh < 768) return 'sm'; if (wh < 992) return 'md'; if (wh < 1260) return 'lg'; return 'xl'; }

addListener(fn) { this.listeners.push(fn); }

addResizeListener(fn) { this.resizeListeners.push(fn); }

removeListener(fn) { _.remove(this.listeners, r => r === fn); }

removeResizeListener(fn) { _.remove(this.resizeListeners, r => r === fn); } }

export function addResp(fn) { if (!RS) RS = new Responsive(); RS.addListener(fn); fn(RS.state); }

export function removeResp(fn) { if (!RS) return; RS.removeListener(fn); }

export function addResize(fn) { if (!RS) RS = new Responsive(); RS.addResizeListener(fn); fn(RS.size); }

export function removeResize(fn) { if (!RS) return; RS.removeResizeListener(fn); }

export function getResp() { if (!RS) RS = new Responsive(); return RS.state; }