Skip to content

Instantly share code, notes, and snippets.

@pichfl
Last active October 4, 2022 19:01
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pichfl/8c4e48e30970a64c295c707339480082 to your computer and use it in GitHub Desktop.
Save pichfl/8c4e48e30970a64c295c707339480082 to your computer and use it in GitHub Desktop.
Media query helper for Ember.js
{{#if (match-media "(max-width:800px)")}}
MediaQuery matches
{{ else}}
MediaQuery doesn't match
{{/if}}
import Helper from '@ember/component/helper';
export default class MatchMedia extends Helper {
_mediaQueryList = null;
_mediaQueryListener = null;
compute([mediaQueryString]) {
return this._attachMatchMedia(mediaQueryString);
}
willDestroy() {
this._detachMatchMedia();
}
_attachMatchMedia(mediaQueryString) {
this._detachMatchMedia();
this._mediaQueryListener = (event) => {
this.recompute(event.matches);
};
this._mediaQueryList = window.matchMedia(mediaQueryString);
this._mediaQueryList.addListener(this._mediaQueryListener);
return this._mediaQueryList.matches;
}
_detachMatchMedia() {
if (this._mediaQueryListener) {
this._mediaQueryList.removeListener(this._mediaQueryListener);
this._mediaQueryList = null;
this._mediaQueryListener = null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment