From 99b3f70b4da5769e3df4463155deb3c368ab49fc Mon Sep 17 00:00:00 2001 From: Krishna Rajendran Date: Tue, 12 Mar 2019 17:31:36 -0700 Subject: [PATCH] Immediately invoke onInit callbacks if amplitude is already initialized --- src/amplitude-client.js | 8 +++++++- test/amplitude-client.js | 16 ++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/amplitude-client.js b/src/amplitude-client.js index b1f4dd41..5d28d5dd 100644 --- a/src/amplitude-client.js +++ b/src/amplitude-client.js @@ -40,6 +40,7 @@ var AmplitudeClient = function AmplitudeClient(instanceName) { this._newSession = false; this._sequenceNumber = 0; this._sessionId = null; + this._isInitialized = false; this._userAgent = (navigator && navigator.userAgent) || null; }; @@ -155,6 +156,7 @@ AmplitudeClient.prototype.init = function init(apiKey, opt_userId, opt_config, o this._onInit[i](); } this._onInit = []; + this._isInitialized = true; }; /** @@ -296,7 +298,11 @@ AmplitudeClient.prototype.isNewSession = function isNewSession() { * @private */ AmplitudeClient.prototype.onInit = function (callback) { - this._onInit.push(callback); + if (this._isInitialized) { + callback(); + } else { + this._onInit.push(callback); + } }; /** diff --git a/test/amplitude-client.js b/test/amplitude-client.js index ac25ee60..551a6b60 100644 --- a/test/amplitude-client.js +++ b/test/amplitude-client.js @@ -65,6 +65,22 @@ describe('AmplitudeClient', function() { assert.ok(onInit2Called); }); + it('should not invoke onInit callbacks before init is called', function() { + let onInitCalled = false; + amplitude.onInit(() => { onInitCalled = true; }); + + assert.ok(onInitCalled === false); + amplitude.init(apiKey); + assert.ok(onInitCalled); + }); + + it('should immediately invoke onInit callbacks if already initialized', function() { + let onInitCalled = false; + amplitude.init(apiKey); + amplitude.onInit(() => { onInitCalled = true; }); + assert.ok(onInitCalled); + }); + it('should clear the onInitQueue', function() { let onInitCalled = false; let onInit2Called = false;