sightglass-overlay.js 1.94 KB
define(function(require) {
    'use strict';
    var Sightglass = require('sightglass');

    function callIt(container, methodName, args) {
        return container[methodName].apply(container, args);
    }
    var tokenStack;
    function sightglass() {
        tokenStack = [];
        try {
            return Sightglass.apply(this, arguments);
        } finally {
            tokenStack = [];
        }
    };
    sightglass.makeOverrideAdapters = function makeOverrideAdapters(parentAdapters, roData) {
        function getStackPath() {
            var currentStackPath = '';
            _.each(tokenStack, function(token) {
                currentStackPath += token.i + token.path;
            });
            return currentStackPath;
        }
        var subAdapters = {};
        _.each(parentAdapters, function(adapterFunctions, interfaceKey) {
            var subAdapter = {};
            _.each(['observe', 'unobserve', 'get', 'set'], function wrapApiMethod(methodName) {
                subAdapter[methodName] = function(obj, key, cbOrValue) {
                    var stackPath = getStackPath();
                    var fullKeyPath = stackPath + interfaceKey + key;
                    if (fullKeyPath in roData) {
                        return callIt(parentAdapters['.'], methodName, [roData, fullKeyPath, cbOrValue]);
                    } else if (stackPath in roData) {
                        obj = roData[stackPath];
                    }
                    try {
                        return callIt(adapterFunctions, methodName, [obj, key, cbOrValue]);
                    } finally {
                        tokenStack.push({i: interfaceKey, path: key});
                    }
                };
            });
            if (adapterFunctions.iterate) {
                subAdapter.iterate = adapterFunctions.iterate;
            }
            subAdapters[interfaceKey] = subAdapter;
        });
        return subAdapters;
    };

    return sightglass;
});