4 * Copyright 2009, Moxiecode Systems AB
5 * Released under LGPL License.
7 * License: http://tinymce.moxiecode.com/license
8 * Contributing: http://tinymce.moxiecode.com/contributing
12 * This class is used to dispatch event to observers/listeners.
13 * All internal events inside TinyMCE uses this class.
15 * @class tinymce.util.Dispatcher
17 * // Creates a custom event
18 * this.onSomething = new tinymce.util.Dispatcher(this);
20 * // Dispatch/fire the event
21 * this.onSomething.dispatch('some string');
23 tinymce.create('tinymce.util.Dispatcher', {
28 * Constructs a new event dispatcher object.
32 * @param {Object} s Optional default execution scope for all observer functions.
34 Dispatcher : function(s) {
35 this.scope = s || this;
40 * Add an observer function to be executed when a dispatch call is done.
43 * @param {function} cb Callback function to execute when a dispatch event occurs.
44 * @param {Object} s Optional execution scope, defaults to the one specified in the class constructor.
45 * @return {function} Returns the same function as the one passed on.
47 add : function(cb, s) {
48 this.listeners.push({cb : cb, scope : s || this.scope});
54 * Add an observer function to be executed to the top of the list of observers.
57 * @param {function} cb Callback function to execute when a dispatch event occurs.
58 * @param {Object} s Optional execution scope, defaults to the one specified in the class constructor.
59 * @return {function} Returns the same function as the one passed on.
61 addToTop : function(cb, s) {
62 this.listeners.unshift({cb : cb, scope : s || this.scope});
68 * Removes an observer function.
71 * @param {function} cb Observer function to remove.
72 * @return {function} The same function that got passed in or null if it wasn't found.
74 remove : function(cb) {
75 var l = this.listeners, o = null;
77 tinymce.each(l, function(c, i) {
89 * Dispatches an event to all observers/listeners.
92 * @param {Object} .. Any number of arguments to dispatch.
93 * @return {Object} Last observer functions return value.
95 dispatch : function() {
96 var s, a = arguments, i, li = this.listeners, c;
98 // Needs to be a real loop since the listener count might change while looping
99 // And this is also more efficient
100 for (i = 0; i<li.length; i++) {
102 s = c.cb.apply(c.scope, a);