Skip to content

Instantly share code, notes, and snippets.

@veryeasily
Last active December 31, 2015 20:39
Show Gist options
  • Save veryeasily/8041980 to your computer and use it in GitHub Desktop.
Save veryeasily/8041980 to your computer and use it in GitHub Desktop.
This is a quick write up using underscore to create getters from a JSON object. A good use case is when the object is a response from an endpoint.
function defineGetters (context, obj) {
this.get = {};
// we iterate over the object via underscore creating getter functions
_.each(obj, function (val, ind, list) {
this.get[ind] = function() {
return ( !_.isObject(val) || _.isArray(val) ? val : $.extend({}, val, true) );
};
}, this);
}
function Item (obj) {
defineGetters(this, obj);
}
var item = new Item({foo: "bar", baz: {fred: "frodo"}});
var temp = item.get.baz();
// => {fred: "frodo"}
temp.fred = "messed up object";
item.get.baz();
// => {fred: "frodo"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment