Last active
May 9, 2020 19:13
-
-
Save sayhicoelho/bb006fd93c814c517a493677b2b3a7a0 to your computer and use it in GitHub Desktop.
Custom EventEmitter for Dart
This file contains hidden or 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
class Listener { | |
final String eventName; | |
final void Function([Object]) callback; | |
Listener(this.eventName, this.callback); | |
} | |
class EventEmitter { | |
final _listeners = <Listener>[]; | |
void addListener(String eventName, void Function([Object]) callback) { | |
this._listeners.add(Listener(eventName, callback)); | |
} | |
void removeListener(String eventName, void Function([Object]) callback) { | |
this._listeners.removeWhere((l) => l.eventName == eventName && l.callback == callback); | |
} | |
void removeAllListeners([String eventName]) { | |
this._listeners.removeWhere((l) => eventName == null || l.eventName == eventName); | |
} | |
void emit(String eventName, [Object data]) { | |
this._listeners.where((l) => l.eventName == eventName).forEach((l) => l.callback(data)); | |
} | |
} | |
// Example | |
void main() { | |
void Function([Object]) listener = ([Object data]) { | |
print(data); | |
}; | |
var eventEmitter = EventEmitter(); | |
eventEmitter.addListener('onChange', listener); | |
eventEmitter.emit('onChange', 'Renan'); | |
eventEmitter.removeListener('onChange', listener); | |
eventEmitter.emit('onChange', 'Coelho'); | |
// Renan | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment