signals.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. /*jslint onevar:true, undef:true, newcap:true, regexp:true, bitwise:true, maxerr:50, indent:4, white:false, nomen:false, plusplus:false */
  2. /*global define:false, require:false, exports:false, module:false, signals:false */
  3. /** @license
  4. * JS Signals <http://millermedeiros.github.com/js-signals/>
  5. * Released under the MIT license
  6. * Author: Miller Medeiros
  7. * Version: 1.0.0 - Build: 268 (2012/11/29 05:48 PM)
  8. */
  9. (function(global){
  10. // SignalBinding -------------------------------------------------
  11. //================================================================
  12. /**
  13. * Object that represents a binding between a Signal and a listener function.
  14. * <br />- <strong>This is an internal constructor and shouldn't be called by regular users.</strong>
  15. * <br />- inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes.
  16. * @author Miller Medeiros
  17. * @constructor
  18. * @internal
  19. * @name SignalBinding
  20. * @param {Signal} signal Reference to Signal object that listener is currently bound to.
  21. * @param {Function} listener Handler function bound to the signal.
  22. * @param {boolean} isOnce If binding should be executed just once.
  23. * @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function).
  24. * @param {Number} [priority] The priority level of the event listener. (default = 0).
  25. */
  26. function SignalBinding(signal, listener, isOnce, listenerContext, priority) {
  27. /**
  28. * Handler function bound to the signal.
  29. * @type Function
  30. * @private
  31. */
  32. this._listener = listener;
  33. /**
  34. * If binding should be executed just once.
  35. * @type boolean
  36. * @private
  37. */
  38. this._isOnce = isOnce;
  39. /**
  40. * Context on which listener will be executed (object that should represent the `this` variable inside listener function).
  41. * @memberOf SignalBinding.prototype
  42. * @name context
  43. * @type Object|undefined|null
  44. */
  45. this.context = listenerContext;
  46. /**
  47. * Reference to Signal object that listener is currently bound to.
  48. * @type Signal
  49. * @private
  50. */
  51. this._signal = signal;
  52. /**
  53. * Listener priority
  54. * @type Number
  55. * @private
  56. */
  57. this._priority = priority || 0;
  58. }
  59. SignalBinding.prototype = {
  60. /**
  61. * If binding is active and should be executed.
  62. * @type boolean
  63. */
  64. active : true,
  65. /**
  66. * Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute`. (curried parameters)
  67. * @type Array|null
  68. */
  69. params : null,
  70. /**
  71. * Call listener passing arbitrary parameters.
  72. * <p>If binding was added using `Signal.addOnce()` it will be automatically removed from signal dispatch queue, this method is used internally for the signal dispatch.</p>
  73. * @param {Array} [paramsArr] Array of parameters that should be passed to the listener
  74. * @return {*} Value returned by the listener.
  75. */
  76. execute : function (paramsArr) {
  77. var handlerReturn, params;
  78. if (this.active && !!this._listener) {
  79. params = this.params? this.params.concat(paramsArr) : paramsArr;
  80. handlerReturn = this._listener.apply(this.context, params);
  81. if (this._isOnce) {
  82. this.detach();
  83. }
  84. }
  85. return handlerReturn;
  86. },
  87. /**
  88. * Detach binding from signal.
  89. * - alias to: mySignal.remove(myBinding.getListener());
  90. * @return {Function|null} Handler function bound to the signal or `null` if binding was previously detached.
  91. */
  92. detach : function () {
  93. return this.isBound()? this._signal.remove(this._listener, this.context) : null;
  94. },
  95. /**
  96. * @return {Boolean} `true` if binding is still bound to the signal and have a listener.
  97. */
  98. isBound : function () {
  99. return (!!this._signal && !!this._listener);
  100. },
  101. /**
  102. * @return {boolean} If SignalBinding will only be executed once.
  103. */
  104. isOnce : function () {
  105. return this._isOnce;
  106. },
  107. /**
  108. * @return {Function} Handler function bound to the signal.
  109. */
  110. getListener : function () {
  111. return this._listener;
  112. },
  113. /**
  114. * @return {Signal} Signal that listener is currently bound to.
  115. */
  116. getSignal : function () {
  117. return this._signal;
  118. },
  119. /**
  120. * Delete instance properties
  121. * @private
  122. */
  123. _destroy : function () {
  124. delete this._signal;
  125. delete this._listener;
  126. delete this.context;
  127. },
  128. /**
  129. * @return {string} String representation of the object.
  130. */
  131. toString : function () {
  132. return '[SignalBinding isOnce:' + this._isOnce +', isBound:'+ this.isBound() +', active:' + this.active + ']';
  133. }
  134. };
  135. /*global SignalBinding:false*/
  136. // Signal --------------------------------------------------------
  137. //================================================================
  138. function validateListener(listener, fnName) {
  139. if (typeof listener !== 'function') {
  140. throw new Error( 'listener is a required param of {fn}() and should be a Function.'.replace('{fn}', fnName) );
  141. }
  142. }
  143. /**
  144. * Custom event broadcaster
  145. * <br />- inspired by Robert Penner's AS3 Signals.
  146. * @name Signal
  147. * @author Miller Medeiros
  148. * @constructor
  149. */
  150. function Signal() {
  151. /**
  152. * @type Array.<SignalBinding>
  153. * @private
  154. */
  155. this._bindings = [];
  156. this._prevParams = null;
  157. // enforce dispatch to aways work on same context (#47)
  158. var self = this;
  159. this.dispatch = function(){
  160. Signal.prototype.dispatch.apply(self, arguments);
  161. };
  162. }
  163. Signal.prototype = {
  164. /**
  165. * Signals Version Number
  166. * @type String
  167. * @const
  168. */
  169. VERSION : '1.0.0',
  170. /**
  171. * If Signal should keep record of previously dispatched parameters and
  172. * automatically execute listener during `add()`/`addOnce()` if Signal was
  173. * already dispatched before.
  174. * @type boolean
  175. */
  176. memorize : false,
  177. /**
  178. * @type boolean
  179. * @private
  180. */
  181. _shouldPropagate : true,
  182. /**
  183. * If Signal is active and should broadcast events.
  184. * <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>
  185. * @type boolean
  186. */
  187. active : true,
  188. /**
  189. * @param {Function} listener
  190. * @param {boolean} isOnce
  191. * @param {Object} [listenerContext]
  192. * @param {Number} [priority]
  193. * @return {SignalBinding}
  194. * @private
  195. */
  196. _registerListener : function (listener, isOnce, listenerContext, priority) {
  197. var prevIndex = this._indexOfListener(listener, listenerContext),
  198. binding;
  199. if (prevIndex !== -1) {
  200. binding = this._bindings[prevIndex];
  201. if (binding.isOnce() !== isOnce) {
  202. throw new Error('You cannot add'+ (isOnce? '' : 'Once') +'() then add'+ (!isOnce? '' : 'Once') +'() the same listener without removing the relationship first.');
  203. }
  204. } else {
  205. binding = new SignalBinding(this, listener, isOnce, listenerContext, priority);
  206. this._addBinding(binding);
  207. }
  208. if(this.memorize && this._prevParams){
  209. binding.execute(this._prevParams);
  210. }
  211. return binding;
  212. },
  213. /**
  214. * @param {SignalBinding} binding
  215. * @private
  216. */
  217. _addBinding : function (binding) {
  218. //simplified insertion sort
  219. var n = this._bindings.length;
  220. do { --n; } while (this._bindings[n] && binding._priority <= this._bindings[n]._priority);
  221. this._bindings.splice(n + 1, 0, binding);
  222. },
  223. /**
  224. * @param {Function} listener
  225. * @return {number}
  226. * @private
  227. */
  228. _indexOfListener : function (listener, context) {
  229. var n = this._bindings.length,
  230. cur;
  231. while (n--) {
  232. cur = this._bindings[n];
  233. if (cur._listener === listener && cur.context === context) {
  234. return n;
  235. }
  236. }
  237. return -1;
  238. },
  239. /**
  240. * Check if listener was attached to Signal.
  241. * @param {Function} listener
  242. * @param {Object} [context]
  243. * @return {boolean} if Signal has the specified listener.
  244. */
  245. has : function (listener, context) {
  246. return this._indexOfListener(listener, context) !== -1;
  247. },
  248. /**
  249. * Add a listener to the signal.
  250. * @param {Function} listener Signal handler function.
  251. * @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function).
  252. * @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)
  253. * @return {SignalBinding} An Object representing the binding between the Signal and listener.
  254. */
  255. add : function (listener, listenerContext, priority) {
  256. validateListener(listener, 'add');
  257. return this._registerListener(listener, false, listenerContext, priority);
  258. },
  259. /**
  260. * Add listener to the signal that should be removed after first execution (will be executed only once).
  261. * @param {Function} listener Signal handler function.
  262. * @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function).
  263. * @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)
  264. * @return {SignalBinding} An Object representing the binding between the Signal and listener.
  265. */
  266. addOnce : function (listener, listenerContext, priority) {
  267. validateListener(listener, 'addOnce');
  268. return this._registerListener(listener, true, listenerContext, priority);
  269. },
  270. /**
  271. * Remove a single listener from the dispatch queue.
  272. * @param {Function} listener Handler function that should be removed.
  273. * @param {Object} [context] Execution context (since you can add the same handler multiple times if executing in a different context).
  274. * @return {Function} Listener handler function.
  275. */
  276. remove : function (listener, context) {
  277. validateListener(listener, 'remove');
  278. var i = this._indexOfListener(listener, context);
  279. if (i !== -1) {
  280. this._bindings[i]._destroy(); //no reason to a SignalBinding exist if it isn't attached to a signal
  281. this._bindings.splice(i, 1);
  282. }
  283. return listener;
  284. },
  285. /**
  286. * Remove all listeners from the Signal.
  287. */
  288. removeAll : function () {
  289. var n = this._bindings.length;
  290. while (n--) {
  291. this._bindings[n]._destroy();
  292. }
  293. this._bindings.length = 0;
  294. },
  295. /**
  296. * @return {number} Number of listeners attached to the Signal.
  297. */
  298. getNumListeners : function () {
  299. return this._bindings.length;
  300. },
  301. /**
  302. * Stop propagation of the event, blocking the dispatch to next listeners on the queue.
  303. * <p><strong>IMPORTANT:</strong> should be called only during signal dispatch, calling it before/after dispatch won't affect signal broadcast.</p>
  304. * @see Signal.prototype.disable
  305. */
  306. halt : function () {
  307. this._shouldPropagate = false;
  308. },
  309. /**
  310. * Dispatch/Broadcast Signal to all listeners added to the queue.
  311. * @param {...*} [params] Parameters that should be passed to each handler.
  312. */
  313. dispatch : function (params) {
  314. if (! this.active) {
  315. return;
  316. }
  317. var paramsArr = Array.prototype.slice.call(arguments),
  318. n = this._bindings.length,
  319. bindings;
  320. if (this.memorize) {
  321. this._prevParams = paramsArr;
  322. }
  323. if (! n) {
  324. //should come after memorize
  325. return;
  326. }
  327. bindings = this._bindings.slice(); //clone array in case add/remove items during dispatch
  328. this._shouldPropagate = true; //in case `halt` was called before dispatch or during the previous dispatch.
  329. //execute all callbacks until end of the list or until a callback returns `false` or stops propagation
  330. //reverse loop since listeners with higher priority will be added at the end of the list
  331. do { n--; } while (bindings[n] && this._shouldPropagate && bindings[n].execute(paramsArr) !== false);
  332. },
  333. /**
  334. * Forget memorized arguments.
  335. * @see Signal.memorize
  336. */
  337. forget : function(){
  338. this._prevParams = null;
  339. },
  340. /**
  341. * Remove all bindings from signal and destroy any reference to external objects (destroy Signal object).
  342. * <p><strong>IMPORTANT:</strong> calling any method on the signal instance after calling dispose will throw errors.</p>
  343. */
  344. dispose : function () {
  345. this.removeAll();
  346. delete this._bindings;
  347. delete this._prevParams;
  348. },
  349. /**
  350. * @return {string} String representation of the object.
  351. */
  352. toString : function () {
  353. return '[Signal active:'+ this.active +' numListeners:'+ this.getNumListeners() +']';
  354. }
  355. };
  356. // Namespace -----------------------------------------------------
  357. //================================================================
  358. /**
  359. * Signals namespace
  360. * @namespace
  361. * @name signals
  362. */
  363. var signals = Signal;
  364. /**
  365. * Custom event broadcaster
  366. * @see Signal
  367. */
  368. // alias for backwards compatibility (see #gh-44)
  369. signals.Signal = Signal;
  370. //exports to multiple environments
  371. if(typeof define === 'function' && define.amd){ //AMD
  372. define(function () { return signals; });
  373. } else if (typeof module !== 'undefined' && module.exports){ //node
  374. module.exports = signals;
  375. } else { //browser
  376. //use string because of Google closure compiler ADVANCED_MODE
  377. /*jslint sub:true */
  378. global['signals'] = signals;
  379. }
  380. }(this));