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 | */ |
Akron | b69cbf1 | 2020-10-01 13:04:44 +0200 | [diff] [blame^] | 9 | /* |
| 10 | * TODO: |
| 11 | * Add a "roll" parameter, like "roll":["left","right","center"] |
| 12 | * and a roll() method, that will switch through the states in the list |
| 13 | * for flexible toggling. |
| 14 | */ |
Akron | 308a603 | 2019-12-05 16:27:34 +0100 | [diff] [blame] | 15 | define(function () { |
| 16 | |
| 17 | "use strict"; |
| 18 | |
| 19 | return { |
| 20 | |
| 21 | /** |
| 22 | * Constructor |
| 23 | */ |
| 24 | create : function (value) { |
| 25 | return Object.create(this)._init(value); |
| 26 | }, |
| 27 | |
| 28 | // Initialize |
| 29 | _init : function (value) { |
| 30 | this._assoc = []; |
| 31 | this.value = value; |
| 32 | return this; |
| 33 | }, |
| 34 | |
| 35 | |
| 36 | /** |
| 37 | * Associate the state with some objects. |
| 38 | */ |
| 39 | associate : function (obj) { |
| 40 | |
| 41 | // Check if the object has a setState() method |
| 42 | if (obj.hasOwnProperty("setState")) { |
| 43 | this._assoc.push(obj); |
| 44 | obj.setState(this.value); |
| 45 | } else { |
| 46 | console.log("Object " + obj + " has no setState() method"); |
| 47 | } |
| 48 | }, |
| 49 | |
| 50 | /** |
| 51 | * Set the state to a certain value. |
| 52 | * This will set the state to all associated objects as well. |
| 53 | */ |
| 54 | set : function (value) { |
| 55 | if (value != this.value) { |
| 56 | this.value = value; |
| 57 | for (let i in this._assoc) { |
| 58 | this._assoc[i].setState(value); |
| 59 | } |
| 60 | }; |
| 61 | }, |
| 62 | |
| 63 | /** |
| 64 | * Get the state value |
| 65 | */ |
| 66 | get : function () { |
| 67 | return this.value; |
Akron | b69cbf1 | 2020-10-01 13:04:44 +0200 | [diff] [blame^] | 68 | }, |
| 69 | |
| 70 | |
| 71 | /** |
| 72 | * Get the number of associated objects |
| 73 | */ |
| 74 | associates : function () { |
| 75 | return this._assoc.length; |
Akron | 308a603 | 2019-12-05 16:27:34 +0100 | [diff] [blame] | 76 | } |
| 77 | } |
| 78 | }); |