-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDoten.pm
60 lines (52 loc) · 1.43 KB
/
Doten.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
module Doten::EXPORT::DEFAULT { }
module Doten {
our @events;
::Doten::EXPORT::DEFAULT<!sub_trait_event-handler> = sub ($trait, $block, $arg) {
my %ns := $block.get_namespace();
my $event;
if defined($arg) {
$event = ~$arg;
}
else {
$event = ~$block;
}
unless defined(%ns<states>) {
%ns<states> = hash();
}
%ns<states>{$event} = $block;
}
sub enqueue (Code $callback) {
@events.push($callback);
}
sub step () {
return unless @events;
my $callback = shift @events;
return $callback();
}
sub run () {
while @events {
step;
}
}
sub post($session, Str $event, *@args, *%named_args) is export {
my $cb = sub {
$session.dispatch($event, |@args, |%named_args);
};
@events.push($cb);
}
class Session {
method post(Str $event, *@args, *%named_args) {
Doten::post(self, $event, |@args, |%named_args);
}
method dispatch (Str $event, *@args, *%named_args) {
my %ns := self.HOW.get_parrotclass(self).get_namespace();
my $handler = %ns<states>{$event};
if defined($handler) {
self.$handler(|@args, |%named_args);
}
else {
warn "unhandled event: $event";
}
}
}
}