Merge M2Ys4U-joinfix
[KiwiIRC.git] / server / irc / eventbinder.js
1 var _ = require('lodash');
2
3
4 module.exports.bindIrcEvents = function (events_scope, event_map, context, irc_connection) {
5 var namespace_prefix = events_scope ?
6 events_scope + ' ' :
7 '';
8
9 // Make sure we have a holder for the bound events
10 if (!event_map._bound_events)
11 event_map._bound_events = {};
12
13 _.each(event_map, function (fn, event_name) {
14 if (event_name[0] === '_') return;
15
16 // Bind the event to `context`, storing it with the event listing
17 if (!event_map._bound_events[event_name]) {
18 event_map._bound_events[event_name] = _.bind(fn, context);
19 }
20
21 // Add the listener to the IRC connection object
22 irc_connection.on(namespace_prefix + event_name, event_map._bound_events[event_name]);
23 });
24 };
25
26
27 module.exports.unbindIrcEvents = function (events_scope, event_map, irc_connection) {
28 var namespace_prefix = events_scope ?
29 events_scope + ' ' :
30 '';
31
32 // No bound events? Then we have nothing to do
33 if (!event_map._bound_events) return;
34
35 _.each(event_map, function(fn, event_name) {
36 if (event_name[0] === '_') return;
37
38 if (event_map._bound_events[event_name]) {
39 // Remove the listener from the IRC connection object
40 irc_connection.removeListener(namespace_prefix + event_name, event_map._bound_events[event_name]);
41
42 // Remove the bound function as no longer needed
43 delete event_map._bound_events[event_name];
44 }
45 });
46
47 delete event_map._bound_events;
48 };