UNPKG

minsky-kit

Version:
109 lines (88 loc) 2.77 kB
// imports import EventDispatcher from './EventDispatcher'; // private statics // class definition export default class MQDefinition extends EventDispatcher { // constructor constructor (args = {}, objectName = 'MQDefinition') { args.debug = args.debug || false; // super super(args, objectName); // set properties this.name = args.name; this._query = args.query; this._weight = args.weight !== undefined ? args.weight : null; this._matches = false; this._listen = false; // set up listener this._mqListener = window.matchMedia(this._query); // set listen value using setter this.listen = args.listen !== undefined ? args.listen : true; // auto check if (args.autoCheck) this.check(); } // methods check () { refreshMatchState.call(this, this._mqListener.matches); } resetMatch () { this._matches = false; } // log (...args) { // // add id to log (todo) // super.log(...args); // } destroy () { // super destroy super.destroy(); } // getters & setters get matches () { return this._matches; } get weight () { return this._weight; } set weight (value) { if (value !== this._weight) { const old = this._weight; this._weight = value; this.dispatch('weightChange', { oldWeight: old, newWeight: this._weight, }); } } get listen () { return this._listen; } set listen (value) { if (value !== this._listen) { this._listen = value; if (value) { if (this._mqListener.addEventListener) { this._mqListener.addEventListener('change', this.blm.add('onMqHit', onMqHit)); } else { this._mqListener.addListener(this.blm.add('onMqHit', onMqHit)); } } else { if (this._mqListener.removeEventListener) { this._mqListener.removeEventListener(this.blm.remove(onMqHit)); } else { this._mqListener.removeListener(this.blm.remove('onMqHit')); } } } } } // Utils function refreshMatchState () { if (this._matches !== this._mqListener.matches) { this._matches = this._mqListener.matches; this.dispatch('matchChange', { matches: this._matches, }); } } // Event handlers function onMqHit (e) { this.log('MediaQuery Hit', this.name, this._query, e.matches); refreshMatchState.call(this, e.matches); }