UNPKG

@gleaner/tracker

Version:

A JavaScript tracking library with ecommerce support

77 lines (66 loc) 1.84 kB
// TODO: cleanup // import "babel-polyfill"; import isFunction from 'lodash.isfunction'; import Gleaner from './gleaner'; import { createInstance } from './utils'; /* Asynchronously Points the queue from bootstraped instance to an actual Gleaner. @param {Function} @param {String} @param {Object} */ function asyncReplaceInstance(instance, name, config) { new Gleaner(name, config, (g) => { if (instance.queue.length) { // gather tracked events let [_, ...events] = instance.queue; // and manually call the track methods events.forEach((e) => g.builder.push(e)); } // point the array loging to working builder instance.queue = g.builder; if (isFunction(config.onLoad)) { config.onLoad(g); } }); } /* Initializes bootstraped instance. @param {Function} bootstraped global function */ export function initBootstraped(instance) { if (isFunction(instance) && instance.queue) { let { name, queue } = instance; // peek at first command let [[method, config]] = queue; if (method === "init") { // create actual instance asyncReplaceInstance(instance, name, config); } else { throw Error("Gleaner: must be initialized with init method."); } } else { throw Error("Gleaner.init expects function created with boostrap script."); } } /* Default exported initializer function for common import/require scenario. @param {String} @param {Object} */ export default function initImported(name, config) { let instance = createInstance(); asyncReplaceInstance(instance, name, config); return instance; } /* Otherwise when not importing (using bootstrap script) this runs and creates instances for the gleaners. */ if (window.GleanerInstances) { let name = GleanerInstances.shift(); // TODO: Multiple instances let instance = window[name]; initBootstraped(instance); }