Skip to content

Instantly share code, notes, and snippets.

@amiel amiel/1_promises.js
Last active Aug 29, 2015

Embed
What would you like to do?
Safe calls before a javascript library is loaded; 2 ideas
// Pattern 1, all access through a promise
function trackEvent() {
var args = arguments;
trackEvent.promise.then(function(library) {
library.trackEvent.apply(null, args);
});
}
trackEvent.promise = new Promise(function(resolve) {
var timer = window.setInterval(function() {
if (libraryisLoaded) {
resolve(library);
window.clearInterval(timer);
}
}, 100);
});
// Pattern 2, push to an array, override push function
// I assume this is how Facebook, _fbq works, but I don't actually know
// UPDATE: I have verified that this is basically how _fbq works.
function trackEvent() {
trackEvent._events.push(arguments);
}
trackEvent._events = [];
trackEvent.timer = window.setInterval(function() {
if (libraryisLoaded) {
window.clearInterval(trackEvent.timer);
var applyEvent = function(args) {
Intercom.apply(null, args);
};
trackEvent._events.push = applyEvent;
for (var args in trackEvent._events) { applyEvent(args); }
}
}, 100);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.