phaser/todo/TS Source/core/Signal.js
2013-09-13 16:16:48 +01:00

250 lines
10 KiB
JavaScript

/// <reference path="../_definitions.ts" />
/**
* Phaser - Signal
*
* A Signal is used for object communication via a custom broadcaster instead of Events.
* Based on JS Signals by Miller Medeiros. Converted by TypeScript by Richard Davey.
* Released under the MIT license
* http://millermedeiros.github.com/js-signals/
*/
var Phaser;
(function (Phaser) {
var Signal = (function () {
function Signal() {
/**
*
* @property _bindings
* @type Array
* @private
*/
this._bindings = [];
/**
*
* @property _prevParams
* @type Any
* @private
*/
this._prevParams = null;
/**
* If Signal should keep record of previously dispatched parameters and
* automatically execute listener during `add()`/`addOnce()` if Signal was
* already dispatched before.
* @type bool
*/
this.memorize = false;
/**
* @type bool
* @private
*/
this._shouldPropagate = true;
/**
* If Signal is active and should broadcast events.
* <p><strong>IMPORTANT:</strong> Setting this property during a dispatch will only affect the next dispatch, if you want to stop the propagation of a signal use `halt()` instead.</p>
* @type bool
*/
this.active = true;
}
Signal.VERSION = '1.0.0';
Signal.prototype.validateListener = /**
*
* @method validateListener
* @param {Any} listener
* @param {Any} fnName
*/
function (listener, fnName) {
if(typeof listener !== 'function') {
throw new Error('listener is a required param of {fn}() and should be a Function.'.replace('{fn}', fnName));
}
};
Signal.prototype._registerListener = /**
* @param {Function} listener
* @param {bool} isOnce
* @param {Object} [listenerContext]
* @param {Number} [priority]
* @return {SignalBinding}
* @private
*/
function (listener, isOnce, listenerContext, priority) {
var prevIndex = this._indexOfListener(listener, listenerContext);
var binding;
if(prevIndex !== -1) {
binding = this._bindings[prevIndex];
if(binding.isOnce() !== isOnce) {
throw new Error('You cannot add' + (isOnce ? '' : 'Once') + '() then add' + (!isOnce ? '' : 'Once') + '() the same listener without removing the relationship first.');
}
} else {
binding = new Phaser.SignalBinding(this, listener, isOnce, listenerContext, priority);
this._addBinding(binding);
}
if(this.memorize && this._prevParams) {
binding.execute(this._prevParams);
}
return binding;
};
Signal.prototype._addBinding = /**
*
* @method _addBinding
* @param {SignalBinding} binding
* @private
*/
function (binding) {
//simplified insertion sort
var n = this._bindings.length;
do {
--n;
}while(this._bindings[n] && binding.priority <= this._bindings[n].priority);
this._bindings.splice(n + 1, 0, binding);
};
Signal.prototype._indexOfListener = /**
*
* @method _indexOfListener
* @param {Function} listener
* @return {number}
* @private
*/
function (listener, context) {
var n = this._bindings.length;
var cur;
while(n--) {
cur = this._bindings[n];
if(cur.getListener() === listener && cur.context === context) {
return n;
}
}
return -1;
};
Signal.prototype.has = /**
* Check if listener was attached to Signal.
* @param {Function} listener
* @param {Object} [context]
* @return {bool} if Signal has the specified listener.
*/
function (listener, context) {
if (typeof context === "undefined") { context = null; }
return this._indexOfListener(listener, context) !== -1;
};
Signal.prototype.add = /**
* Add a listener to the signal.
* @param {Function} listener Signal handler function.
* @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function).
* @param {Number} [priority] The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0)
* @return {SignalBinding} An Object representing the binding between the Signal and listener.
*/
function (listener, listenerContext, priority) {
if (typeof listenerContext === "undefined") { listenerContext = null; }
if (typeof priority === "undefined") { priority = 0; }
this.validateListener(listener, 'add');
return this._registerListener(listener, false, listenerContext, priority);
};
Signal.prototype.addOnce = /**
* Add listener to the signal that should be removed after first execution (will be executed only once).
* @param {Function} listener Signal handler function.
* @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function).
* @param {Number} [priority] The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0)
* @return {SignalBinding} An Object representing the binding between the Signal and listener.
*/
function (listener, listenerContext, priority) {
if (typeof listenerContext === "undefined") { listenerContext = null; }
if (typeof priority === "undefined") { priority = 0; }
this.validateListener(listener, 'addOnce');
return this._registerListener(listener, true, listenerContext, priority);
};
Signal.prototype.remove = /**
* Remove a single listener from the dispatch queue.
* @param {Function} listener Handler function that should be removed.
* @param {Object} [context] Execution context (since you can add the same handler multiple times if executing in a different context).
* @return {Function} Listener handler function.
*/
function (listener, context) {
if (typeof context === "undefined") { context = null; }
this.validateListener(listener, 'remove');
var i = this._indexOfListener(listener, context);
if(i !== -1) {
this._bindings[i]._destroy();
this._bindings.splice(i, 1);
}
return listener;
};
Signal.prototype.removeAll = /**
* Remove all listeners from the Signal.
*/
function () {
if(this._bindings) {
var n = this._bindings.length;
while(n--) {
this._bindings[n]._destroy();
}
this._bindings.length = 0;
}
};
Signal.prototype.getNumListeners = /**
* @return {number} Number of listeners attached to the Signal.
*/
function () {
return this._bindings.length;
};
Signal.prototype.halt = /**
* Stop propagation of the event, blocking the dispatch to next listeners on the queue.
* <p><strong>IMPORTANT:</strong> should be called only during signal dispatch, calling it before/after dispatch won't affect signal broadcast.</p>
* @see Signal.prototype.disable
*/
function () {
this._shouldPropagate = false;
};
Signal.prototype.dispatch = /**
* Dispatch/Broadcast Signal to all listeners added to the queue.
* @param {...*} [params] Parameters that should be passed to each handler.
*/
function () {
var paramsArr = [];
for (var _i = 0; _i < (arguments.length - 0); _i++) {
paramsArr[_i] = arguments[_i + 0];
}
if(!this.active) {
return;
}
var n = this._bindings.length;
var bindings;
if(this.memorize) {
this._prevParams = paramsArr;
}
if(!n) {
//should come after memorize
return;
}
bindings = this._bindings.slice(0)//clone array in case add/remove items during dispatch
;
this._shouldPropagate = true//in case `halt` was called before dispatch or during the previous dispatch.
;
//execute all callbacks until end of the list or until a callback returns `false` or stops propagation
//reverse loop since listeners with higher priority will be added at the end of the list
do {
n--;
}while(bindings[n] && this._shouldPropagate && bindings[n].execute(paramsArr) !== false);
};
Signal.prototype.forget = /**
* Forget memorized arguments.
* @see Signal.memorize
*/
function () {
this._prevParams = null;
};
Signal.prototype.dispose = /**
* Remove all bindings from signal and destroy any reference to external objects (destroy Signal object).
* <p><strong>IMPORTANT:</strong> calling any method on the signal instance after calling dispose will throw errors.</p>
*/
function () {
this.removeAll();
delete this._bindings;
delete this._prevParams;
};
Signal.prototype.toString = /**
* @return {string} String representation of the object.
*/
function () {
return '[Signal active:' + this.active + ' numListeners:' + this.getNumListeners() + ']';
};
return Signal;
})();
Phaser.Signal = Signal;
})(Phaser || (Phaser = {}));