Merge branch 'development' into server_plugins
[KiwiIRC.git] / server / modules.js
1 var events = require('events'),
2 util = require('util');
3
4
5 // Where events are bound to
6 var active_publisher;
7
8
9 // Create a publisher to allow event subscribing
10 function Publisher (obj) {
11 var EventPublisher = function modulePublisher() {};
12 util.inherits(EventPublisher, events.EventEmitter);
13
14 return new EventPublisher();
15 }
16
17
18 // Register an already created Publisher() as the active instance
19 function registerPublisher (obj) {
20 active_publisher = obj;
21 }
22
23
24
25
26 /**
27 * Module object
28 * To be created by modules to bind to server events
29 */
30 function Module (module_name) {}
31
32
33 // Holder for all the bound events by this module
34 Module.prototype._events = {};
35
36
37 // Keep track of this modules events and bind
38 Module.prototype.subscribe = function (event_name, fn) {
39 this._events[event_name] = this._events[event_name] || [];
40 this._events[event_name].push(fn);
41
42 active_publisher.on(event_name, fn);
43 };
44
45
46 // Keep track of this modules events and bind once
47 Module.prototype.once = function (event_name, fn) {
48 this._events[event_name] = this._events[event_name] || [];
49 this._events[event_name].push(fn);
50
51 active_publisher.once(event_name, fn);
52 };
53
54
55 // Remove any events by this module only
56 Module.prototype.unsubscribe = function (event_name, fn) {
57 var idx;
58
59 if (typeof event_name === 'undefined') {
60 // Remove all events
61 this._events = [];
62
63 } else if (typeof fn === 'undefined') {
64 // Remove all of 1 event type
65 delete this._events[event_name];
66
67 } else {
68 // Remove a single event + callback
69 for (idx in (this._events[event_name] || [])) {
70 if (this._events[event_name][idx] === fn) {
71 delete this._events[event_name][idx];
72 }
73 }
74 }
75
76 active_publisher.removeListener(event_name, fn);
77 };
78
79
80 // Clean up anything used by this module
81 Module.prototype.dispose = function () {
82 this.unsubscribe();
83 };
84
85
86
87
88
89
90 module.exports = {
91 // Objects
92 Module: Module,
93 Publisher: Publisher,
94
95 // Methods
96 registerPublisher: registerPublisher
97 };