Last active
December 31, 2015 20:39
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
See also: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Defining_getters_and_setters