Skip to content

Instantly share code, notes, and snippets.

@sujeetkv
Last active June 17, 2019 09:05
Show Gist options
  • Save sujeetkv/2eb10b64561cd571fe2641634a672fe2 to your computer and use it in GitHub Desktop.
Save sujeetkv/2eb10b64561cd571fe2641634a672fe2 to your computer and use it in GitHub Desktop.
Simple State-Observer in JavaScript
/**
* Simple State-Observer in JavaScript
*/
var PropState = function () {
var _self = this;
var _state = {};
var _callbacks = {};
if (arguments.length) {
for (var i in arguments) {
var obj = arguments[i];
if (obj.name && obj.value) {
_state[obj.name] = obj.value;
_callbacks[obj.name] = obj.onChange;
(function (propName) {
Object.defineProperty(_self, propName, {
get: function () {
return _state[propName];
},
set: function (value) {
var oldValue = _state[propName];
_state[propName] = value;
if (value !== oldValue) {
_self.onChange(_state, propName, value);
if (typeof _callbacks[propName] === 'function') {
_callbacks[propName](propName, value);
}
}
},
enumerable: true,
configurable: false,
});
})(obj.name);
}
}
}
};
Object.defineProperty(PropState.prototype, 'onChange', {
value: function (state, key, value) {},
writable: true,
enumerable: false,
configurable: false,
});
// define global state change callback
PropState.prototype.onChange = function (state, key, value) {
console.log('Object State updated ', state);
};
// initialize all states
var propState = new PropState(
{name: 'a', value: 1, onChange: function (key, value) { console.log(key+' updated', value); }},
{name: 'b', value: 2, onChange: function (key, value) { console.log(key+' updated', value); }},
{name: 'c', value: 3}
);
console.log(propState.a);
propState.a = 3; // change state to invoke its callback
console.log(propState.a);
// get all states
for (var stateName in propState) {
console.log(propState[stateName]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment