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 "dispatcher.hh"
20 class dispatcher::impl
24 impl(dispatcher
* dispatcher
) :
25 dispatcher_(dispatcher
),
28 dispatcher::handle
getNewHandle()
31 dispatcher::handle
handle(dispatcher_
->impl_
, id_
);
35 typedef std::pair
<unsigned,dispatcher::function
> callback
;
36 typedef std::multimap
<std::string
,callback
> callback_lookup
;
37 typedef callback_lookup::iterator callback_it
;
39 typedef std::multimap
<unsigned,std::string
> handle_lookup
;
40 typedef handle_lookup::iterator handle_it
;
43 handle
add_target(const std::string
& event
,
44 const function
& callback
,
47 callbacks_
.insert(std::make_pair(event
, std::make_pair(handle
.id(),
49 handles_
.insert(std::make_pair(handle
.id(), event
));
54 void remove_target(unsigned id
)
56 std::pair
<handle_it
,handle_it
> matching(handles_
.equal_range(id
));
58 for (handle_it it
= matching
.first
; it
!= matching
.second
; ++it
)
60 callback_it first
= callbacks_
.find((*it
).second
);
61 callback_it last
= callbacks_
.end();
63 for (callback_it jt
= first
; jt
!= last
; ++jt
)
65 if ((*jt
).second
.first
== id
)
76 void dispatch(const std::string
& event
)
78 std::pair
<callback_it
,callback_it
>
79 callbacks(callbacks_
.equal_range(event
));
81 for (callback_it it
= callbacks
.first
; it
!= callbacks
.second
; ++it
)
83 function callback
= (*it
).second
.second
;
89 dispatcher
* dispatcher_
;
93 callback_lookup callbacks_
;
94 handle_lookup handles_
;
98 void dispatcher::handle::clear()
100 boost::shared_ptr
<impl
> dispatcher
;
101 if (id_
&& (dispatcher
= dispatcher_
.lock()))
103 dispatcher
->remove_target(id_
);
109 dispatcher::dispatcher() :
110 impl_(new dispatcher::impl(this)) {}
113 dispatcher::handle
dispatcher::add_target(const std::string
& event
,
114 const function
& callback
)
116 return add_target(event
, callback
, impl_
->getNewHandle());
119 dispatcher::handle
dispatcher::add_target(const std::string
& event
,
120 const function
& callback
,
124 return impl_
->add_target(event
, callback
, handle
);
128 void dispatcher::remove_target(unsigned id
)
131 return impl_
->remove_target(id
);
135 void dispatcher::dispatch(const std::string
& event
)
138 impl_
->dispatch(event
);
142 dispatcher
& dispatcher::global()
144 static dispatcher dispatcher
;