]>
Commit | Line | Data |
---|---|---|
24c7594d BB |
1 | (function() { |
2 | var Disposable, Emitter; | |
3 | ||
4 | Disposable = require('./disposable'); | |
5 | ||
6 | module.exports = Emitter = (function() { | |
7 | Emitter.prototype.isDisposed = false; | |
8 | ||
9 | ||
10 | /* | |
11 | Section: Construction and Destruction | |
12 | */ | |
13 | ||
14 | function Emitter() { | |
15 | this.handlersByEventName = {}; | |
16 | } | |
17 | ||
18 | Emitter.prototype.dispose = function() { | |
19 | this.handlersByEventName = null; | |
20 | return this.isDisposed = true; | |
21 | }; | |
22 | ||
23 | ||
24 | /* | |
25 | Section: Event Subscription | |
26 | */ | |
27 | ||
28 | Emitter.prototype.on = function(eventName, handler) { | |
29 | var currentHandlers; | |
30 | if (this.isDisposed) { | |
31 | throw new Error("Emitter has been disposed"); | |
32 | } | |
33 | if (typeof handler !== 'function') { | |
34 | throw new Error("Handler must be a function"); | |
35 | } | |
36 | if (currentHandlers = this.handlersByEventName[eventName]) { | |
37 | this.handlersByEventName[eventName] = currentHandlers.concat(handler); | |
38 | } else { | |
39 | this.handlersByEventName[eventName] = [handler]; | |
40 | } | |
41 | return new Disposable(this.off.bind(this, eventName, handler)); | |
42 | }; | |
43 | ||
44 | Emitter.prototype.off = function(eventName, handlerToRemove) { | |
45 | var handler, newHandlers, oldHandlers, _i, _len; | |
46 | if (this.isDisposed) { | |
47 | return; | |
48 | } | |
49 | if (oldHandlers = this.handlersByEventName[eventName]) { | |
50 | newHandlers = []; | |
51 | for (_i = 0, _len = oldHandlers.length; _i < _len; _i++) { | |
52 | handler = oldHandlers[_i]; | |
53 | if (handler !== handlerToRemove) { | |
54 | newHandlers.push(handler); | |
55 | } | |
56 | } | |
57 | return this.handlersByEventName[eventName] = newHandlers; | |
58 | } | |
59 | }; | |
60 | ||
61 | ||
62 | /* | |
63 | Section: Event Emission | |
64 | */ | |
65 | ||
66 | Emitter.prototype.emit = function(eventName, value) { | |
67 | var handler, handlers, _i, _len, _ref; | |
68 | if (handlers = (_ref = this.handlersByEventName) != null ? _ref[eventName] : void 0) { | |
69 | for (_i = 0, _len = handlers.length; _i < _len; _i++) { | |
70 | handler = handlers[_i]; | |
71 | handler(value); | |
72 | } | |
73 | } | |
74 | }; | |
75 | ||
76 | return Emitter; | |
77 | ||
78 | })(); | |
79 | ||
80 | }).call(this); |