2 /*] Copyright (c) 2009-2010, Charles McGarvey [**************************
3 **] All rights reserved.
7 * Distributable under the terms and conditions of the 2-clause BSD license;
8 * see the file COPYING for a complete text of the license.
10 **************************************************************************/
14 #include "Dispatch.hh"
27 Dispatch::Handler
getNewHandler()
30 //return Dispatch::Handler(this, mId);
31 Dispatch::Handler
handler(this, mId
);
35 typedef std::pair
<unsigned,Dispatch::Function
> Callback
;
36 typedef std::multimap
<std::string
,Callback
> CallbackLookup
;
37 typedef CallbackLookup::iterator CallbackIter
;
39 typedef std::multimap
<unsigned,std::string
> HandlerLookup
;
40 typedef HandlerLookup::iterator HandlerIter
;
43 inline Handler
addHandler(const std::string
& event
,
44 const Function
& callback
, Handler handler
)
46 mCallbacks
.insert(std::make_pair(event
,
47 std::make_pair(handler
.getId(), callback
)));
48 mHandlers
.insert(std::make_pair(handler
.getId(), event
));
53 inline void removeHandler(unsigned id
)
55 std::pair
<HandlerIter
,HandlerIter
>
56 matching(mHandlers
.equal_range(id
));
58 for (HandlerIter it
= matching
.first
; it
!= matching
.second
; ++it
)
60 CallbackIter first
= mCallbacks
.find((*it
).second
);
61 CallbackIter last
= mCallbacks
.end();
63 for (CallbackIter jt
= first
; jt
!= last
; ++jt
)
65 if ((*jt
).second
.first
== id
)
76 void dispatch(const std::string
& event
, const Message
* message
)
78 std::pair
<CallbackIter
,CallbackIter
>
79 callbacks(mCallbacks
.equal_range(event
));
81 for (CallbackIter it
= callbacks
.first
; it
!= callbacks
.second
;
84 Function callback
= (*it
).second
.second
;
92 CallbackLookup mCallbacks
;
93 HandlerLookup mHandlers
;
97 Dispatch::Handler::~Handler()
101 mDispatch
->removeHandler(mId
);
106 Dispatch::Dispatch() :
107 mImpl(new Dispatch::Impl
) {}
110 Dispatch::Handler
Dispatch::addHandler(const std::string
& event
,
111 const Function
& callback
)
113 return addHandler(event
, callback
, mImpl
->getNewHandler());
116 Dispatch::Handler
Dispatch::addHandler(const std::string
& event
,
117 const Function
& callback
,
121 return mImpl
->addHandler(event
, callback
, handler
);
125 void Dispatch::removeHandler(unsigned id
)
128 return mImpl
->removeHandler(id
);
132 void Dispatch::dispatch(const std::string
& event
, const Message
* message
)
135 mImpl
->dispatch(event
, message
);