Wed, 31 Dec 2014 07:53:36 +0100
Correct small whitespace inconsistency, lost while renaming variables.
michael@0 | 1 | /* This Source Code Form is subject to the terms of the Mozilla Public |
michael@0 | 2 | * License, v. 2.0. If a copy of the MPL was not distributed with this |
michael@0 | 3 | * file, you can obtain one at http://mozilla.org/MPL/2.0/. */ |
michael@0 | 4 | |
michael@0 | 5 | var EXPORTED_SYMBOLS = ['addListener', 'addObject', |
michael@0 | 6 | 'removeListener', |
michael@0 | 7 | 'sendMessage', 'log', 'pass', 'fail']; |
michael@0 | 8 | |
michael@0 | 9 | var listeners = {}; |
michael@0 | 10 | |
michael@0 | 11 | // add a listener for a specific message type |
michael@0 | 12 | function addListener(msgType, listener) { |
michael@0 | 13 | if (listeners[msgType] === undefined) { |
michael@0 | 14 | listeners[msgType] = []; |
michael@0 | 15 | } |
michael@0 | 16 | |
michael@0 | 17 | listeners[msgType].push(listener); |
michael@0 | 18 | } |
michael@0 | 19 | |
michael@0 | 20 | // add each method in an object as a message listener |
michael@0 | 21 | function addObject(object) { |
michael@0 | 22 | for (var msgType in object) { |
michael@0 | 23 | addListener(msgType, object[msgType]); |
michael@0 | 24 | } |
michael@0 | 25 | } |
michael@0 | 26 | |
michael@0 | 27 | // remove a listener for all message types |
michael@0 | 28 | function removeListener(listener) { |
michael@0 | 29 | for (var msgType in listeners) { |
michael@0 | 30 | for (let i = 0; i < listeners.length; ++i) { |
michael@0 | 31 | if (listeners[msgType][i] == listener) { |
michael@0 | 32 | listeners[msgType].splice(i, 1); // remove listener from array |
michael@0 | 33 | } |
michael@0 | 34 | } |
michael@0 | 35 | } |
michael@0 | 36 | } |
michael@0 | 37 | |
michael@0 | 38 | function sendMessage(msgType, obj) { |
michael@0 | 39 | if (listeners[msgType] === undefined) { |
michael@0 | 40 | return; |
michael@0 | 41 | } |
michael@0 | 42 | |
michael@0 | 43 | for (let i = 0; i < listeners[msgType].length; ++i) { |
michael@0 | 44 | listeners[msgType][i](obj); |
michael@0 | 45 | } |
michael@0 | 46 | } |
michael@0 | 47 | |
michael@0 | 48 | function log(obj) { |
michael@0 | 49 | sendMessage('log', obj); |
michael@0 | 50 | } |
michael@0 | 51 | |
michael@0 | 52 | function pass(obj) { |
michael@0 | 53 | sendMessage('pass', obj); |
michael@0 | 54 | } |
michael@0 | 55 | |
michael@0 | 56 | function fail(obj) { |
michael@0 | 57 | sendMessage('fail', obj); |
michael@0 | 58 | } |