Akron | 308a603 | 2019-12-05 16:27:34 +0100 | [diff] [blame] | 1 | /** |
| 2 | * Create a state object, that can have a single value |
| 3 | * (mostly boolean) and multiple objects associated to it. |
| 4 | * Whenever the state changes, all objects are informed |
| 5 | * by their setState() method of the value change. |
| 6 | * |
| 7 | * @author Nils Diewald |
| 8 | */ |
| 9 | define(function () { |
| 10 | |
| 11 | "use strict"; |
| 12 | |
| 13 | return { |
| 14 | |
| 15 | /** |
| 16 | * Constructor |
| 17 | */ |
| 18 | create : function (value) { |
| 19 | return Object.create(this)._init(value); |
| 20 | }, |
| 21 | |
| 22 | // Initialize |
| 23 | _init : function (value) { |
| 24 | this._assoc = []; |
| 25 | this.value = value; |
| 26 | return this; |
| 27 | }, |
| 28 | |
| 29 | |
| 30 | /** |
| 31 | * Associate the state with some objects. |
| 32 | */ |
| 33 | associate : function (obj) { |
| 34 | |
| 35 | // Check if the object has a setState() method |
| 36 | if (obj.hasOwnProperty("setState")) { |
| 37 | this._assoc.push(obj); |
| 38 | obj.setState(this.value); |
| 39 | } else { |
| 40 | console.log("Object " + obj + " has no setState() method"); |
| 41 | } |
| 42 | }, |
| 43 | |
| 44 | /** |
| 45 | * Set the state to a certain value. |
| 46 | * This will set the state to all associated objects as well. |
| 47 | */ |
| 48 | set : function (value) { |
| 49 | if (value != this.value) { |
| 50 | this.value = value; |
| 51 | for (let i in this._assoc) { |
| 52 | this._assoc[i].setState(value); |
| 53 | } |
| 54 | }; |
| 55 | }, |
| 56 | |
| 57 | /** |
| 58 | * Get the state value |
| 59 | */ |
| 60 | get : function () { |
| 61 | return this.value; |
| 62 | } |
| 63 | } |
| 64 | }); |