Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save gibbok/f6a32a6c3509273315b85a53ee03f9c6 to your computer and use it in GitHub Desktop.
Save gibbok/f6a32a6c3509273315b85a53ee03f9c6 to your computer and use it in GitHub Desktop.
GibboK - Pattern OLOO applied to object serialization and deserialization
(function (window) {
// example of OLOO pattern applied to object se serialization and deserialization
var dataApi = '{"id":0,"top":10,"left":20,"width":100,"height":150}';
var state = JSON.parse(dataApi);
var base = {
init: function (data) {
var _data = data; // private
// defined on object itself not on its protoype
Object.defineProperty(this, 'id', {
get: function () {
return _data.id;
},
set: function (value) {
_data.id = value;
}
});
Object.defineProperty(this, 'top', {
get: function () {
return _data.top;
},
set: function (value) {
_data.top = value;
}
});
Object.defineProperty(this, 'left', {
get: function () {
return _data.left;
},
set: function (value) {
_data.left = value;
}
});
Object.defineProperty(this, 'width', {
get: function () {
return _data.width;
},
set: function (value) {
_data.width = value;
}
});
Object.defineProperty(this, 'height', {
get: function () {
return _data.height;
},
set: function (value) {
_data.height = value;
}
});
this.toJson = function () {
return JSON.stringify(_data);
}
},
// defined on protoype
fromJson: function (json) {
var data = JSON.parse(json),
obj = Object.create(this);
obj.init(data);
return obj;
}
};
// create object with linked prototype using deserialization
var wdgA = base.fromJson(dataApi);
console.log(wdgA);
// serialize object
var str = wdgA.toJson();
console.log(str);
// create object with data injection
var wdgB = Object.create(base);
wdgB.init(state);
var id = wdgB.id;
console.log(id);
})(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment