UNPKG

3 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3var SideralObject_1 = require("./../SideralObject");
4/**
5 * This class is used to generate events and properly destroy it when a SideralObject is killed
6 */
7var Signal = (function () {
8 /* METHODS */
9 /**
10 * @constructor
11 * @param parent - The parent of the signal
12 */
13 function Signal(parent, onBind, onUnbind) {
14 /**
15 * List of listeners connected to the signal
16 * @private
17 */
18 this._listeners = [];
19 if (!(parent instanceof SideralObject_1.SideralObject)) {
20 throw new Error("Signal.constructor: an instance of SideralObject must be passed on the constructor (the owner of the signal).");
21 }
22 this.parent = parent;
23 this.onBind = onBind;
24 this.onUnbind = onUnbind;
25 }
26 /**
27 * Dispatch a signal to all listeners with parameters
28 * @param params - Parameters
29 */
30 Signal.prototype.dispatch = function () {
31 var params = [];
32 for (var _i = 0; _i < arguments.length; _i++) {
33 params[_i] = arguments[_i];
34 }
35 if (typeof this._listeners === "undefined") {
36 console.log([this, this.parent], this._listeners);
37 }
38 this._listeners.forEach(function (listener) { return listener.apply(void 0, params); });
39 };
40 /**
41 * Add a listener to the current signal
42 * @param listener - The listener
43 * @returns The listener
44 */
45 Signal.prototype.add = function (listener) {
46 this._listeners.push(listener);
47 if (this.onBind) {
48 this.onBind(listener);
49 }
50 return listener;
51 };
52 /**
53 * Remove a listener from the signal
54 * @param listener - The listener to remove
55 * @returns True if listener has been removed
56 */
57 Signal.prototype.remove = function (listener) {
58 var nextListeners = this._listeners.filter(function (x) { return x !== listener; }), hasRemoved = nextListeners.length !== this._listeners.length;
59 this._listeners = nextListeners;
60 if (this.onUnbind && hasRemoved) {
61 this.onUnbind(listener);
62 }
63 return hasRemoved;
64 };
65 /**
66 * Remove all listeners from the signal
67 */
68 Signal.prototype.removeAll = function () {
69 this._listeners.forEach(this.remove.bind(this));
70 this._listeners = [];
71 };
72 /**
73 * Bind a listener by the first parameter of a trigger
74 * @param param - The parameter binded to the listener
75 * @param listener - The listener
76 * @returns The listener
77 */
78 Signal.prototype.bind = function (param, listener) {
79 var params = [].concat(param);
80 return this.add(function (key) {
81 if (typeof key === "string" && params.find(function (x) { return x === key; })) {
82 listener.apply(void 0, [].slice.call(arguments, 1));
83 }
84 });
85 };
86 return Signal;
87}());
88exports.Signal = Signal;