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; |
Akron | 678c26f | 2020-10-09 08:52:50 +0200 | [diff] [blame^] | 57 | this._assoc.forEach(i => i.setState(value)); |
Akron | 308a603 | 2019-12-05 16:27:34 +0100 | [diff] [blame] | 58 | }; |
| 59 | }, |
| 60 | |
| 61 | /** |
| 62 | * Get the state value |
| 63 | */ |
| 64 | get : function () { |
| 65 | return this.value; |
Akron | b69cbf1 | 2020-10-01 13:04:44 +0200 | [diff] [blame] | 66 | }, |
| 67 | |
| 68 | |
| 69 | /** |
| 70 | * Get the number of associated objects |
| 71 | */ |
| 72 | associates : function () { |
| 73 | return this._assoc.length; |
Akron | 38ed5dc | 2020-10-01 17:33:00 +0200 | [diff] [blame] | 74 | }, |
| 75 | |
| 76 | /** |
| 77 | * Clear all associated objects |
| 78 | */ |
| 79 | clear : function () { |
| 80 | return this._assoc = []; |
Akron | 308a603 | 2019-12-05 16:27:34 +0100 | [diff] [blame] | 81 | } |
| 82 | } |
| 83 | }); |