Skip to content

Commit

Permalink
Move listener instantiation out of constructor (ReactTraining#139)
Browse files Browse the repository at this point in the history
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 ReactTraining#139 by removing the root
of the issue instead of covering it up with my previous PR.
  • Loading branch information
stevenwcarter committed Nov 21, 2019
1 parent 5728ae7 commit b497414
Showing 1 changed file with 8 additions and 6 deletions.
14 changes: 8 additions & 6 deletions modules/MediaQueryListener.js
Original file line number Diff line number Diff line change
@@ -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);
Expand All @@ -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;
}
Expand Down

0 comments on commit b497414

Please sign in to comment.