Virtual dot notation access
by bladnman
HTML
<script src="https://raw.github.com/carhartl/jquery-cookie/master/jquery.cookie.js"></script>
<script src="http://qubedpeas.com/files/currentVersion/QPTools.js"></script>
<input type=button id="theButton" value="run test" class="runButton">
<div id="log" class="log"></div>
CSS
.runButton {
width: 125px;
margin: 20px;
}
.log {
padding:10px;
margin: 20px;
border: 1px dotted #ccc;
color:#888;
font-face: arial;
font-size:12px;
background: #fbfbfb;
}
JavaScript
/* ************************************ */
function runTest() {
var dog = {
name : "Sally",
breed : "Cocker Spaniel",
info : {
size : "Medium",
color : "Golden",
"favorite-saying" : function () {
return "Don't call me fat!"
}
}
};
log("name:", getValueFromObject(dog, "name"));
log("breed:", getValueFromObject(dog, "breed"));
log("info.size:", getValueFromObject(dog, "info.size"));
log("info.size.time:", getValueFromObject(dog, "info.size.time"));
log("info.nothing.here:", getValueFromObject(dog, "info.nothing.here"));
log("info.favorite-saying:", getValueFromObject(dog, "info.favorite-saying"));
}
function getValueFromObject(obj, str) {
if ( QPU.isNoE(obj) || QPU.isNoE(str) ) {
return undefined;
}
if ( ! QPU.contains(str, ".") ) {
return obj[str];
}
var parts = str.split(".");
var outVal = obj;
for (var i = 0; i < parts.length; i++) {
var partName = parts[i];
if ( QPU.isNoE(outVal[partName] )) {
return undefined;
}
var thisVal = outVal[partName];
if (QPU.isFunction(thisVal)) {
outVal = thisVal();
}
else {
outVal = thisVal;
}
}
return outVal;
}
/* ************************************
_____ ___ __ __ ___ _ _ _____ ___
|_ _| __| \/ | _ \ | /_\_ _| __|
| | | _|| |\/| | _/ |__ / _ \| | | _|
|_| |___|_| |_|_| |____/_/ \_\_| |___|
************************************ */
function log(message, value) {
var outMessage = message;
if (typeof value !== "undefined" && value !== null) {
outMessage += " [" + value + "]";
}
if ($("#log").html() != "") {
$("#log").append("<br>");
}
$("#log").append(outMessage);
if (window.console && console.log) {
...