|
1 /* This Source Code Form is subject to the terms of the Mozilla Public |
|
2 * License, v. 2.0. If a copy of the MPL was not distributed with this file, |
|
3 * You can obtain one at http://mozilla.org/MPL/2.0/. */ |
|
4 |
|
5 "use strict"; |
|
6 |
|
7 this.EXPORTED_SYMBOLS = ["GlobalState"]; |
|
8 |
|
9 const EXPORTED_METHODS = ["getState", "clear", "get", "set", "delete", "setFromState"]; |
|
10 /** |
|
11 * Module that contains global session data. |
|
12 */ |
|
13 function GlobalState() { |
|
14 let internal = new GlobalStateInternal(); |
|
15 let external = {}; |
|
16 for (let method of EXPORTED_METHODS) { |
|
17 external[method] = internal[method].bind(internal); |
|
18 } |
|
19 return Object.freeze(external); |
|
20 } |
|
21 |
|
22 function GlobalStateInternal() { |
|
23 // Storage for global state. |
|
24 this.state = {}; |
|
25 } |
|
26 |
|
27 GlobalStateInternal.prototype = { |
|
28 /** |
|
29 * Get all value from the global state. |
|
30 */ |
|
31 getState: function() { |
|
32 return this.state; |
|
33 }, |
|
34 |
|
35 /** |
|
36 * Clear all currently stored global state. |
|
37 */ |
|
38 clear: function() { |
|
39 this.state = {}; |
|
40 }, |
|
41 |
|
42 /** |
|
43 * Retrieve a value from the global state. |
|
44 * |
|
45 * @param aKey |
|
46 * A key the value is stored under. |
|
47 * @return The value stored at aKey, or an empty string if no value is set. |
|
48 */ |
|
49 get: function(aKey) { |
|
50 return this.state[aKey] || ""; |
|
51 }, |
|
52 |
|
53 /** |
|
54 * Set a global value. |
|
55 * |
|
56 * @param aKey |
|
57 * A key to store the value under. |
|
58 */ |
|
59 set: function(aKey, aStringValue) { |
|
60 this.state[aKey] = aStringValue; |
|
61 }, |
|
62 |
|
63 /** |
|
64 * Delete a global value. |
|
65 * |
|
66 * @param aKey |
|
67 * A key to delete the value for. |
|
68 */ |
|
69 delete: function(aKey) { |
|
70 delete this.state[aKey]; |
|
71 }, |
|
72 |
|
73 /** |
|
74 * Set the current global state from a state object. Any previous global |
|
75 * state will be removed, even if the new state does not contain a matching |
|
76 * key. |
|
77 * |
|
78 * @param aState |
|
79 * A state object to extract global state from to be set. |
|
80 */ |
|
81 setFromState: function (aState) { |
|
82 this.state = (aState && aState.global) || {}; |
|
83 } |
|
84 }; |