Last active
July 5, 2018 03:48
-
-
Save clinyong/3b9fa3bf9d1d53d3b30a8702331e0e16 to your computer and use it in GitHub Desktop.
Minimum react event pool
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const eventPool = []; | |
const EVENT_POOL_SIZE = 10; | |
function SyntheticEvent(nativeEvent) { | |
this.nativeEvent = nativeEvent; | |
} | |
SyntheticEvent.prototype.persist = function persist() { | |
this.isPersistent = true; | |
}; | |
SyntheticEvent.prototype.destructor = function destructor() { | |
this.nativeEvent = null; | |
}; | |
export function getPooledEvent(nativeEvent) { | |
if (eventPool.length) { | |
const instance = eventPool.pop(); | |
// We should not use class here, or will throw Class constructor cannot be invoked without 'new' | |
return SyntheticEvent.call(instance, nativeEvent); | |
} else { | |
return new SyntheticEvent(nativeEvent); | |
} | |
} | |
export function releasePooledEvent(evt) { | |
evt.destructor(); | |
if (eventPool.length < EVENT_POOL_SIZE) { | |
eventPool.push(evt); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment