-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample.cpp
60 lines (45 loc) · 1.51 KB
/
example.cpp
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
struct WidgetEventArgs {
explicit WidgetEventArgs(std::string _reversedString) : reversedString(_reversedString) { }
std::string reversedString;
};
class Widget {
public:
void reverseString(std::string s) {
auto reversedS = std::string(s.rbegin(), s.rend());
// fire stringReversed event
// method 1:
stringReversed.fire(WidgetEventArgs(reversedS));
// method 2:
stringReversed(WidgetEventArgs(reversedS));
}
Event<WidgetEventArgs> stringReversed;
};
class Consumer {
public:
Consumer() {
// event subscription to a member function
_widget.stringReversed.bind(&Consumer::_onStringReversed1, this);
_widget.stringReversed.bind(&Consumer::_onStringReversed2, this);
// ignore subscription if handler function already subscribed:
_widget.stringReversed.bind(&Consumer::_onStringReversed2, this, EventFlag::ONLY_UNIQUE);
// unsubscribe event
_widget.stringReversed.unbind(&Consumer::_onStringReversed2, this);
// subscribe a lambda
_widget.stringReversed += [](auto e) {
std::cout << e.reversedString << " from lambda\n";
};
_widget.reverseString("Hello");
}
private:
Widget _widget;
void _onStringReversed1(WidgetEventArgs e) {
std::cout << e.reversedString << 1 << std::endl;
}
void _onStringReversed2(WidgetEventArgs e) {
std::cout << e.reversedString << 2 << std::endl;
}
};
int main() {
Consumer c;
return 0;
}