Last active
December 19, 2015 16:19
-
-
Save captainbrosset/5982630 to your computer and use it in GitHub Desktop.
AriaTemplates singleton utility to help with safely getting nested properties from the data model.
This file contains hidden or 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
/** | |
* Data model utility functions | |
*/ | |
Aria.classDefinition({ | |
$classpath : 'utils.Model', | |
$singleton : true, | |
$prototype : { | |
/** | |
* Safely try to get the value of a nested property of an object. If it is not found, return the default value | |
* instead. This could be useful in some cases when looking up values in a big data model, however if it doesn't | |
* find the property, it is not going to tell you which of the part of the chain failed, so if this information is | |
* important to you, don't use this function | |
* @param {Object} model A javascript object | |
* @param {String} path The full path to access the property, e.g. 'inbound.flight.type.destination' | |
* @param {Object} def The default to return in case the property does not exist. This can be any type | |
* @return {Object} The value of the property if found or the default value otherwise | |
*/ | |
get : function (model, path, def) { | |
path = path || ''; | |
model = model || {}; | |
def = def || ''; | |
var parts = path.split('.'); | |
if (parts.length > 1 && typeof model[parts[0]] === 'object') { | |
return this.get(model[parts[0]], parts.splice(1).join('.'), def); | |
} else { | |
return model[parts[0]] || def; | |
} | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment