wmakeev
8/23/2014 - 11:56 PM

Tasting (Taist addon)

Tasting (Taist addon)

/**
 * Tasting
 * Date: 24.08.14
 * Vitaliy V. Makeev (w.makeev@gmail.com)
 */

function init() {
    var taistApi;

    var loadScript = function (src, cb) {
        var head = document.head || document.getElementsByTagName('head')[0];
        var script = document.createElement('script');

        cb = cb || function() {};

        script.type = 'text/javascript';
        script.charset = 'utf8';
        script.async = true;
        script.src = src;

        var onend = stdOnEnd;
        onend(script, cb);

        head.appendChild(script)
    };

    var stdOnEnd = function (script, cb) {
        script.onload = function () {
            this.onerror = this.onload = null;
            cb()
        };
        script.onerror = function () {
            // this.onload = null here is necessary
            // because even IE9 works not like others
            this.onerror = this.onload = null
            cb(new Error('Failed to load ' + this.src))
        }
    };

    var getContext = function (pkg, cb) {
        var addonId = pkg.name
          , deps = pkg.tasting.dependencies;

        var paths = {};
        for (var depName in deps) {
            paths[depName] = deps[depName].slice(-3) === '.js'
                ? deps[depName].substring(0, deps[depName].length - 3)
                : deps[depName];
        }

        var contextRequire = require.config({
            context: addonId,
            paths: paths
        });

        var requireList = ['require'].concat(Object.keys(pkg.tasting.dependencies))

        contextRequire(requireList, function (require) {
            cb(null, require);
            taistApi.log('[' + pkg.name + '] addon is started');
        });
    };

    var addonEntry = {
        start: function(_taistApi, entryPoint) {
            taistApi = _taistApi;

            var tasting = {};

            tasting.getContext = getContext;

            loadScript('https://cdn.jsdelivr.net/requirejs/2.1.14/require.min.js', function (err) {
                if (err) throw err;
                taistApi.log('RequireJS ' + requirejs.version + ' injected.');
                window.Tasting = tasting;
            });
        }
    };

    return addonEntry;
}