Skip to content

Instantly share code, notes, and snippets.

@iconifyit
Created January 25, 2020 17:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iconifyit/c10de8adc6bd8e24e5fb31aa8376f557 to your computer and use it in GitHub Desktop.
Save iconifyit/c10de8adc6bd8e24e5fb31aa8376f557 to your computer and use it in GitHub Desktop.
Dynamically create a JavaScript class (POJSO) with getters and setters from a JSON object.
/**
* Creates Javascript Model class with getters and setters for each property in a JSON object.
* For instance, if you call :
*
* var model = JsonToModel({name : 'Scott'});
*
* You will get back:
*
* function() {
* this.instance = 'Model@000-000000';
* this.name;
*
* this.getName = function() {
* return this.name
* }
*
* this.setName = function(value) {
* this.name = value;
* return this.name;
* }
* }
*/
(function(global) {
var JsonToModel = function(data) {
var Model = function() {
this.instance = 'Model@' + generateUUID();
}
for (var key in data) {
var value = data[key];
var getter = "get"+ucWords(key),
setter = "set"+ucWords(key);
Model[key] = data[key];
Model.prototype[getter] = new Function('return this.' + key);
Model.prototype[setter] = new Function(
'value',
'this.' + key + ' = value;\nreturn this.' + key + ';'
);
}
var model = new Model();
for (var key in data) {
var value = data[key],
getter = "get"+ucWords(key),
setter = "set"+ucWords(key);
model[setter](value);
}
return model;
}
global.JsonToModel = JsonToModel;
})(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment