blob: 78cd4cc08a3d12f7a62e6f2319b8dc0e000eced2 [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;
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;
Akronb69cbf12020-10-01 13:04:44 +020068 },
69
70
71 /**
72 * Get the number of associated objects
73 */
74 associates : function () {
75 return this._assoc.length;
Akron38ed5dc2020-10-01 17:33:00 +020076 },
77
78 /**
79 * Clear all associated objects
80 */
81 clear : function () {
82 return this._assoc = [];
Akron308a6032019-12-05 16:27:34 +010083 }
84 }
85});