2 /*] Copyright (c) 2009-2011, Charles McGarvey [*****************************
3 **] All rights reserved.
5 * Distributable under the terms and conditions of the 2-clause BSD license;
6 * see the file COPYING for a complete text of the license.
8 *****************************************************************************/
12 #include "dispatcher.hh"
18 class dispatcher::impl
22 impl(dispatcher
* dispatcher
) :
23 dispatcher_(dispatcher
),
26 dispatcher::handle
new_handle()
28 dispatcher::handle
handle(dispatcher_
->impl_
, --id_
);
32 typedef std::pair
<unsigned,dispatcher::function
> callback
;
33 typedef std::multimap
<std::string
,callback
> callback_lookup
;
34 typedef callback_lookup::iterator callback_it
;
36 typedef std::multimap
<unsigned,std::string
> handle_lookup
;
37 typedef handle_lookup::iterator handle_it
;
39 handle
add_target(const std::string
& event
,
40 const function
& callback
, handle handle
)
42 callbacks_
.insert(std::make_pair(event
,
43 std::make_pair(handle
.id(), callback
)));
44 handles_
.insert(std::make_pair(handle
.id(), event
));
48 void remove_target(unsigned id
)
50 std::pair
<handle_it
,handle_it
> matching(handles_
.equal_range(id
));
52 for (handle_it it
= matching
.first
;
53 it
!= matching
.second
; ++it
)
55 callback_it first
= callbacks_
.find((*it
).second
);
56 callback_it last
= callbacks_
.end();
58 for (callback_it jt
= first
; jt
!= last
; ++jt
)
60 if ((*jt
).second
.first
== id
)
71 void dispatch(const std::string
& event
)
73 std::pair
<callback_it
,callback_it
>
74 callbacks(callbacks_
.equal_range(event
));
76 for (callback_it it
= callbacks
.first
; it
!= callbacks
.second
; ++it
)
78 function callback
= (*it
).second
.second
;
83 dispatcher
* dispatcher_
;
86 callback_lookup callbacks_
;
87 handle_lookup handles_
;
90 void dispatcher::handle::clear()
92 boost::shared_ptr
<impl
> dispatcher
;
93 if (id_
&& (dispatcher
= dispatcher_
.lock()))
95 dispatcher
->remove_target(id_
);
101 dispatcher::dispatcher() :
102 impl_(new dispatcher::impl(this)) {}
105 dispatcher::add_target(const std::string
& event
, const function
& callback
)
107 return add_target(event
, callback
, impl_
->new_handle());
110 dispatcher::handle
dispatcher::add_target(const std::string
& event
,
111 const function
& callback
, handle handle
)
114 return impl_
->add_target(event
, callback
, handle
);
117 void dispatcher::remove_target(unsigned id
)
120 return impl_
->remove_target(id
);
123 void dispatcher::dispatch(const std::string
& event
)
126 impl_
->dispatch(event
);
129 dispatcher
& dispatcher::global()
131 static dispatcher dispatcher
;