Skip to content

Instantly share code, notes, and snippets.

@paulresdat
Last active October 26, 2020 03:50
Show Gist options
  • Save paulresdat/8fa9c6ce4ba14fe58b3a8a28f5514b18 to your computer and use it in GitHub Desktop.
Save paulresdat/8fa9c6ce4ba14fe58b3a8a28f5514b18 to your computer and use it in GitHub Desktop.
Event Handling in Dart
Type typeof<T>() => T;
typedef void DelegateHandler<T>(T response);
abstract class IHandler {
void run(dynamic response);
bool isType<T>(T type);
dynamic get();
}
class Handler<T> implements IHandler {
T type;
DelegateHandler<T> _handler;
Handler(DelegateHandler<T> handler) {
_handler = handler;
}
T cast<T>(x) => x is T ? x : null;
void run(dynamic response) {
_handler(cast<T>(response));
}
bool isType<T2>(T2 type) {
if (type is T) {
return true;
}
return false;
}
DelegateHandler<T> get() {
return _handler;
}
}
abstract class IDelegate<T> {
void subscribe(DelegateHandler<T> handler);
void remove(DelegateHandler<T> handler);
void invoke(T response);
}
class Delegate<T> implements IDelegate<T> {
final _handlers = new List<IHandler>();
void subscribe(DelegateHandler<T> handler) {
_handlers.add(Handler(handler));
}
void invoke(T response) {
_handlers.forEach((element) {
if (element.isType(response)) {
element.run(response);
}
});
}
void remove(DelegateHandler<T> handler) {
int indexSplice;
for (var i = 0; i < _handlers.length; i++) {
if (_handlers[i].get() == handler) {
indexSplice = i;
}
}
_handlers.removeAt(indexSplice);
}
}
// use
class MyClass {
final IDelegate<String> errorDelegate = Delegate();
void testError(String message) {
errorDelegate.invoke(message);
}
}
class MyParentClass {
final MyClass dep = MyClass();
MyParentClass() {
dep.errorDelegate.subscribe((message) {
print("ANONYMOUS $message");
});
dep.errorDelegate.subscribe(subscribeError);
dep.testError("test 123");
dep.errorDelegate.remove(subscribeError);
dep.testError("test 123 again");
}
void subscribeError(String message) {
print("SUBSCRIBE ERROR: $message");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment