MrLesion
7/31/2019 - 6:23 PM

namespacer.js

var e4 = e4 || {};

e4.data = {
    collection: {
        get: function(strPropertyPath, obj) {
            if (!strPropertyPath) {
                throw new Error('No property path defined');
            }

            obj = obj || window;

            var arrProperties = strPropertyPath.split('.');

            for (var i = 0; i < arrProperties.length; i++) {
                var prop = arrProperties[i];

                if (!obj.hasOwnProperty(prop)) {
                    arrProperties.pop();
                    throw new Error('Cannot read property "' + prop + '" on ' + arrProperties.join('.'));
                } else {
                    obj = obj[prop];
                }
            }

            return obj;
        },
        set: function(strPropertyPath, anyValue, obj, setRecursively) {
            if (!strPropertyPath) {
                throw new Error('No property path defined');
            }

            obj = obj || window;
            setRecursively = setRecursively || true;

            var intPropertyPathDepth = 0,
                arrProperties = strPropertyPath.split('.');

            arrProperties.reduce(function(a, b) {
                intPropertyPathDepth++;

                if (setRecursively === true && typeof a[b] === 'undefined' && intPropertyPathDepth !== arrProperties.length) {
                    a[b] = {};
                    return a[b];
                }

                if (intPropertyPathDepth === arrProperties.length) {
                    a[b] = anyValue || {};
                    return anyValue || {};
                } else {
                    return a[b];
                }
            }, obj);
        }
    }  
};


/*
<script>
    @{
        string propertyPath = string.Format( "e4.data.dealersearch.{0}", Espresso.Id );
    }
    e4.data.collection.set("@propertyPath", @JsonService.Instance.ToJson( json ));
</script>
*/