From b497414bac6d7c0fad95a85ed3b54de631016c2e Mon Sep 17 00:00:00 2001 From: Steven Carter Date: Thu, 21 Nov 2019 01:32:30 -0500 Subject: [PATCH] Move listener instantiation out of constructor (#139) I suspected that the issue lay in the listener being created in the constructor, and playing havoc with the `this` scope so I broke it out into its own function and passed the necessary parameters in. This succeeded in resolving the issue reported in #139 by removing the root of the issue instead of covering it up with my previous PR. --- modules/MediaQueryListener.js | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/modules/MediaQueryListener.js b/modules/MediaQueryListener.js index 29fa673..087c1e1 100644 --- a/modules/MediaQueryListener.js +++ b/modules/MediaQueryListener.js @@ -1,3 +1,10 @@ +const createListener = (nativeMediaQueryList, matches, active, listener) => (...args) => { + matches = nativeMediaQueryList.matches; + if (active) { + listener(...args); + } +} + export default class MediaQueryListener { constructor(targetWindow, query, listener) { this.nativeMediaQueryList = targetWindow.matchMedia(query); @@ -6,12 +13,7 @@ export default class MediaQueryListener { // when the listener is already waiting in the event queue. // Having an active flag to make sure the listener is not called // after we removeListener. - this.cancellableListener = (...args) => { - this.matches = this.nativeMediaQueryList.matches; - if (this.active) { - listener(...args); - } - }; + this.cancellableListener = createListener(this.nativeMediaQueryList, this.matches, this.active, listener); this.nativeMediaQueryList.addListener(this.cancellableListener); this.matches = this.nativeMediaQueryList.matches; }