blob: a5ab7d8da92e1fced42132cba250cf87d226a448 [file] [log] [blame]
Akron308a6032019-12-05 16:27:34 +01001/**
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 */
Akronb69cbf12020-10-01 13:04:44 +02009/*
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 */
Akron308a6032019-12-05 16:27:34 +010015define(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;
Akron678c26f2020-10-09 08:52:50 +020057 this._assoc.forEach(i => i.setState(value));
Akron308a6032019-12-05 16:27:34 +010058 };
59 },
60
61 /**
62 * Get the state value
63 */
64 get : function () {
65 return this.value;
Akronb69cbf12020-10-01 13:04:44 +020066 },
67
68
69 /**
70 * Get the number of associated objects
71 */
72 associates : function () {
73 return this._assoc.length;
Akron38ed5dc2020-10-01 17:33:00 +020074 },
75
76 /**
77 * Clear all associated objects
78 */
79 clear : function () {
80 return this._assoc = [];
Akron308a6032019-12-05 16:27:34 +010081 }
82 }
83});