1 /** 2 * Copyright (C) 2013 KO GmbH <copyright@kogmbh.com> 3 * 4 * @licstart 5 * This file is part of WebODF. 6 * 7 * WebODF is free software: you can redistribute it and/or modify it 8 * under the terms of the GNU Affero General Public License (GNU AGPL) 9 * as published by the Free Software Foundation, either version 3 of 10 * the License, or (at your option) any later version. 11 * 12 * WebODF is distributed in the hope that it will be useful, but 13 * WITHOUT ANY WARRANTY; without even the implied warranty of 14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 * GNU Affero General Public License for more details. 16 * 17 * You should have received a copy of the GNU Affero General Public License 18 * along with WebODF. If not, see <http://www.gnu.org/licenses/>. 19 * @licend 20 * 21 * @source: http://www.webodf.org/ 22 * @source: https://github.com/kogmbh/WebODF/ 23 */ 24 25 /*global core, runtime*/ 26 27 /** 28 * @constructor 29 * @param {!Array.<!string>=} eventIds 30 */ 31 core.EventNotifier = function EventNotifier(eventIds) { 32 "use strict"; 33 34 var /**@type{!Object.<!string,!Array.<!Function>>}*/ 35 eventListener = {}; 36 37 /** 38 * @param {!string} eventId 39 * @param {*} args 40 * @return {undefined} 41 */ 42 this.emit = function (eventId, args) { 43 var i, subscribers; 44 45 runtime.assert(eventListener.hasOwnProperty(eventId), 46 "unknown event fired \"" + eventId + "\""); 47 subscribers = eventListener[eventId]; 48 // runtime.log("firing event \"" + eventId + "\" to " + subscribers.length + " subscribers."); 49 for (i = 0; i < subscribers.length; i += 1) { 50 subscribers[i](args); 51 } 52 }; 53 54 /** 55 * @param {!string} eventId 56 * @param {!Function} cb 57 * @return {undefined} 58 */ 59 this.subscribe = function (eventId, cb) { 60 runtime.assert(eventListener.hasOwnProperty(eventId), 61 "tried to subscribe to unknown event \"" + eventId + "\""); 62 eventListener[eventId].push(cb); 63 }; 64 65 /** 66 * @param {!string} eventId 67 * @param {!Function} cb 68 * @return {undefined} 69 */ 70 this.unsubscribe = function (eventId, cb) { 71 var cbIndex; 72 runtime.assert(eventListener.hasOwnProperty(eventId), 73 "tried to unsubscribe from unknown event \"" + eventId + "\""); 74 75 cbIndex = eventListener[eventId].indexOf(cb); 76 runtime.assert(cbIndex !== -1, "tried to unsubscribe unknown callback from event \"" + eventId + "\""); 77 if (cbIndex !== -1) { 78 eventListener[eventId].splice(cbIndex, 1); 79 } 80 }; 81 82 /** 83 * Register an event 84 * @param {!string} eventId 85 * @return {undefined} 86 */ 87 function register(eventId) { 88 runtime.assert(!eventListener.hasOwnProperty(eventId), "Duplicated event ids: \"" + eventId + "\" registered more than once."); 89 eventListener[eventId] = []; 90 } 91 this.register = register; 92 93 /** 94 * @return {undefined} 95 */ 96 function init() { 97 if (eventIds) { 98 eventIds.forEach(register); 99 } 100 } 101 102 init(); 103 }; 104