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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
|
/*
* Observable.cpp
* FirmwareRefactorPrep
*
* Created by Lou Amadio on 10/18/08.
* Copyright 2008 OoeyGUI. All rights reserved.
*
*/
#include "WProgram.h"
#include "Collections.h"
#include "Observable.h"
struct forEachNotifyContext
{
void* observerContext;
uint32_t event;
forEachNotifyContext(uint32_t evt, void* oc = NULL)
: observerContext(oc)
, event(evt)
{
}
};
void forEachFireEvent(void* item, void* context)
{
forEachNotifyContext* ctx = (forEachNotifyContext*)context;
((Observer*)item)->notify(ctx->event, ctx->observerContext);
}
Observable::Observable()
{
}
Observable::~Observable()
{
notifyObservers(ObservedEvent_Destroyed, this);
}
void Observable::notifyObservers(uint32_t eventId, void* context)
{
forEachNotifyContext ctx(eventId, context);
_observers.foreach(forEachFireEvent, &ctx);
}
bool Observable::hasObservers()
{
return _observers.count() > 0;
}
void Observable::addObserver(Observer* o)
{
if (!_observers.find(o))
{
_observers.push(o);
o->notify(ObservedEvent_Attached, this);
}
}
void Observable::removeObserver(Observer* o)
{
size_t index;
if (_observers.find(o, &index))
{
((Observer*)_observers[index])->notify(ObservedEvent_Detached, this);
_observers.remove(index);
}
}
Observer::Observer()
{
}
void removeObserver(void* item, void* context)
{
((Observable*)item)->removeObserver((Observer*)context);
}
Observer::~Observer()
{
_observing.foreach(removeObserver, this);
}
void Observer::notify(uint32_t eventId, void* context)
{
switch (eventId)
{
case ObservedEvent_Attached:
if (!_observing.find(context))
_observing.push(context);
break;
case ObservedEvent_Destroyed:
case ObservedEvent_Detached:
{
size_t index;
if (_observing.find(context, &index))
_observing.remove(index);
}
break;
}
}
|