Skip to content

Commit 5f048c7

Browse files
authored
Immediately invoke onInit callbacks if amplitude is already initialized (#179)
1 parent cd7bfce commit 5f048c7

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

src/amplitude-client.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ var AmplitudeClient = function AmplitudeClient(instanceName) {
4040
this._newSession = false;
4141
this._sequenceNumber = 0;
4242
this._sessionId = null;
43+
this._isInitialized = false;
4344

4445
this._userAgent = (navigator && navigator.userAgent) || null;
4546
};
@@ -155,6 +156,7 @@ AmplitudeClient.prototype.init = function init(apiKey, opt_userId, opt_config, o
155156
this._onInit[i]();
156157
}
157158
this._onInit = [];
159+
this._isInitialized = true;
158160
};
159161

160162
/**
@@ -296,7 +298,11 @@ AmplitudeClient.prototype.isNewSession = function isNewSession() {
296298
* @private
297299
*/
298300
AmplitudeClient.prototype.onInit = function (callback) {
299-
this._onInit.push(callback);
301+
if (this._isInitialized) {
302+
callback();
303+
} else {
304+
this._onInit.push(callback);
305+
}
300306
};
301307

302308
/**

test/amplitude-client.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,22 @@ describe('AmplitudeClient', function() {
6565
assert.ok(onInit2Called);
6666
});
6767

68+
it('should not invoke onInit callbacks before init is called', function() {
69+
let onInitCalled = false;
70+
amplitude.onInit(() => { onInitCalled = true; });
71+
72+
assert.ok(onInitCalled === false);
73+
amplitude.init(apiKey);
74+
assert.ok(onInitCalled);
75+
});
76+
77+
it('should immediately invoke onInit callbacks if already initialized', function() {
78+
let onInitCalled = false;
79+
amplitude.init(apiKey);
80+
amplitude.onInit(() => { onInitCalled = true; });
81+
assert.ok(onInitCalled);
82+
});
83+
6884
it('should clear the onInitQueue', function() {
6985
let onInitCalled = false;
7086
let onInit2Called = false;

0 commit comments

Comments
 (0)