Support default values in state manager, so they won't be serialized
Change-Id: I68730ff303fb5e3ed74fca172fe733598037be22
diff --git a/dev/js/spec/stateSpec.js b/dev/js/spec/stateSpec.js
index 5fb6e71..996eca4 100644
--- a/dev/js/spec/stateSpec.js
+++ b/dev/js/spec/stateSpec.js
@@ -181,7 +181,6 @@
expect(serial["glemm"]).toEqual(false);
});
-
it('should serialize correctly', function () {
const el = document.createElement('input');
const sm = stateManagerClass.create(el);
@@ -206,5 +205,31 @@
expect(sm.toString().indexOf("\"z\":\"b\"")).not.toEqual(-1);
expect(sm.toString().indexOf("\"a\":\"d\"")).toEqual(-1);
});
+
+ it('should accept and not serialize default values', function () {
+ const el = document.createElement('input');
+ const sm = stateManagerClass.create(el);
+ expect(sm).toBeTruthy();
+
+ const s1 = sm.newState('test', [1,2,3], 1);
+
+ expect(sm.toString()).toEqual("");
+
+ s1.set(2);
+
+ expect(sm.toString()).toEqual("\"test\":2");
+
+ s1.set(3);
+
+ expect(sm.toString()).toEqual("\"test\":3");
+
+ s1.set(1);
+
+ expect(sm.toString()).toEqual("");
+
+ s1.set(2);
+
+ expect(sm.toString()).toEqual("\"test\":2");
+ });
});
});
diff --git a/dev/js/src/state/manager.js b/dev/js/src/state/manager.js
index 6d7fe11..4376b27 100644
--- a/dev/js/src/state/manager.js
+++ b/dev/js/src/state/manager.js
@@ -24,6 +24,7 @@
_init : function (element) {
this._e = element;
this._states = {};
+ this._defaults = {};
this._parse(element.value);
return this;
@@ -34,8 +35,6 @@
_parse : function (value) {
if (value === undefined || value === '')
return;
-
-
this._states = JSON.parse('{' + value + '}');
},
@@ -59,7 +58,7 @@
// Create new state that is automatically associated
// with the state manager
- newState : function (name, values) {
+ newState : function (name, values, defValue) {
const t = this;
let s = stateClass.create(values);
@@ -68,11 +67,23 @@
if (t._states[name] !== undefined) {
s.set(t._states[name]);
};
+
+ // Set default value
+ // TODO: It would be better to make this part
+ // of the state and serialize correctly using TOJSON()
+ if (defValue !== undefined) {
+ s.setIfNotYet(defValue);
+ t._defaults[name] = defValue;
+ };
// Associate with dummy object
s.associate({
setState : function (value) {
- t._states[name] = value;
+ if (t._defaults[name] !== undefined && t._defaults[name] == value) {
+ delete t._states[name];
+ } else {
+ t._states[name] = value;
+ };
t._update();
}
});