Callbacks Reference
Complete reference for all callback signatures, patterns, and best practices for handling asynchronous responses in the Moitribe SDK.
CallbackFunction Type
The base callback type used throughout the SDK.
type CallbackFunction<T = any> = (result: T) => void;
Basic Usage:
const callback = (result) => {
console.log('Callback received:', result);
};
TypeScript Usage:
interface MyResult {
success: boolean;
data?: any;
message?: string;
}
const callback: CallbackFunction<MyResult> = (result) => {
if (result.success) {
console.log('Success:', result.data);
} else {
console.error('Error:', result.message);
}
};
Core SDK Callbacks
Initialization Callback
Called when SDK initialization completes.
MoitribeSDK('my-game-id', 'init', {
noui: true
}, (result) => {
// result: { success: boolean }
if (result.success) {
console.log('SDK initialized successfully');
} else {
console.error('SDK initialization failed');
}
});
Authentication Callbacks
Login Callback
Called during authentication flows (init, social login, OTP login).
MoitribeSDK('my-game-id', 'init', {
noui: true,
loginCallback: (result) => {
// result: { success: boolean, profile?: SignedInProfile, message?: string }
if (result.success) {
console.log('Logged in:', result.profile.name);
} else {
console.log('Login failed:', result.message);
}
}
}, (result) => {
console.log('Init complete:', result);
});
Authentication Status Callback
Called when checking authentication status.
MoitribeSDK('my-game-id', 'isAuthenticated', {}, (result) => {
// result: { success: boolean, authenticated?: boolean, profile?: SignedInProfile }
if (result.success && result.authenticated) {
console.log('Player is authenticated:', result.profile.name);
} else {
console.log('Player not authenticated');
}
});
OTP Generation Callback
Called when OTP is generated for email/phone.
MoitribeSDK('my-game-id', 'genOtp', {
emailid: 'player@example.com'
}, (result) => {
// result: { success: boolean, message?: string }
if (result.success) {
console.log('OTP sent successfully');
} else {
console.error('OTP generation failed:', result.message);
}
});
OTP Login Callback
Called when authenticating with OTP.
MoitribeSDK('my-game-id', 'loginWithOtp', {
emailid: 'player@example.com',
otp: '123456'
}, (result) => {
// result: { success: boolean, profile?: SignedInProfile, message?: string }
if (result.success) {
console.log('OTP login successful:', result.profile.name);
} else {
console.error('OTP login failed:', result.message);
}
});
Social Login Callback
Called when authenticating with social platforms.
MoitribeSDK('my-game-id', 'loginWithSocial', {
social: {
socialplat: 'google',
id: 'google-user-id',
name: 'Player Name',
email: 'player@example.com'
}
}, (result) => {
// result: { success: boolean, profile?: SignedInProfile, message?: string }
if (result.success) {
console.log('Social login successful:', result.profile.name);
} else {
console.error('Social login failed:', result.message);
}
});
Profile Callbacks
Profile Update Callback
Called when updating player profile.
MoitribeSDK('my-game-id', 'updateProfile', {
name: 'New Display Name'
}, (result) => {
// result: { success: boolean, profile?: SignedInProfile, message?: string }
if (result.success) {
console.log('Profile updated:', result.profile.name);
} else {
console.error('Profile update failed:', result.message);
}
});
Leaderboard Callbacks
Leaderboard Metadata Callback
Called when loading leaderboard metadata.
MoitribeSDK('my-game-id', 'loadleaderboardmetadata', {
onlyData: true
}, (result) => {
// result: { success: boolean, leaderboards?: LeaderboardMeta[], message?: string }
if (result.success && result.leaderboards) {
result.leaderboards.forEach(leaderboard => {
console.log(`Leaderboard: ${leaderboard.leaderboardName}`);
});
} else {
console.error('Failed to load metadata:', result.message);
}
});
Top Scores Callback
Called when retrieving top scores from leaderboard.
MoitribeSDK('my-game-id', 'loadleaderboardtopscores', {
leaderboardid: 'high-scores',
collection: 1,
timespan: 0,
maxresults: 50,
onlyData: true
}, (result) => {
// result: { success: boolean, scores?: LeaderboardScoreData[], message?: string }
if (result.success && result.scores) {
result.scores.forEach(score => {
console.log(`${score.playerRank}. ${score.playerName}: ${score.playerScore}`);
});
} else {
console.error('Failed to load scores:', result.message);
}
});
Score Submission Callback
Called when submitting score to leaderboard.
MoitribeSDK('my-game-id', 'submitscore', {
leaderboardid: 'high-scores',
score: 1500,
scoretag: 'level-5-completed'
}, (result) => {
// result: { success: boolean, rank?: number, message?: string }
if (result.success) {
console.log('Score submitted successfully');
if (result.rank) {
console.log(`New rank: ${result.rank}`);
}
} else {
console.error('Score submission failed:', result.message);
}
});
Real-Time Multiplayer Callbacks
RTM Standard Room Callbacks
Room Creation Callback
MoitribeSDK('my-game-id', 'createstandardroom', {
variant: 1,
min_automatch_players: 2,
max_automatch_players: 4,
onRoomCreated: (status, room) => {
// status: boolean
// room: Room
if (status) {
console.log('Room created:', room.roomID);
console.log('Participants:', room.getParticipantsIDs);
} else {
console.error('Room creation failed');
}
}
}, (result) => {
console.log('Create room initiated:', result);
});
Room Join Callback
MoitribeSDK('my-game-id', 'joinstandardroominvcode', {
invitationID: 'room-invite-code',
onJoinedRoom: (status, room) => {
// status: boolean
// room: Room
if (status) {
console.log('Joined room:', room.roomID);
console.log('My participant ID:', room.participants.find(p => p.playerID === 'my-id')?.participantID);
} else {
console.error('Failed to join room');
}
}
}, (result) => {
console.log('Join room initiated:', result);
});
Room Leave Callback
MoitribeSDK('my-game-id', 'leavestandardroom', {}, (result) => {
// result: { success: boolean }
console.log('Leave room initiated:', result);
});
// Also handle via callback in room params
const roomParams = {
onLeftRoom: (status, roomID) => {
// status: boolean
// roomID: string
if (status) {
console.log('Left room successfully:', roomID);
} else {
console.error('Failed to leave room');
}
}
};
Room Connection Callback
const roomParams = {
onRoomConnected: (status, room) => {
// status: boolean
// room: Room
if (status) {
console.log('Connected to room:', room.roomID);
console.log('Room status:', room.status);
} else {
console.error('Room connection failed');
}
}
};
Message Received Callback
const roomParams = {
onMessageReceived: (messageData, senderParticipantID, isReliable) => {
// messageData: ArrayBuffer
// senderParticipantID: string
// isReliable: boolean
// Parse the message
const view = new DataView(messageData);
const messageType = view.getUint8(0);
const messageValue = view.getUint32(1, true);
console.log(`Received ${isReliable ? 'reliable' : 'unreliable'} message from ${senderParticipantID}`);
console.log(`Type: ${messageType}, Value: ${messageValue}`);
// Handle different message types
switch (messageType) {
case 1: // Position update
handlePositionUpdate(senderParticipantID, messageValue);
break;
case 2: // Game action
handleGameAction(senderParticipantID, messageValue);
break;
}
}
};
Peer Event Callbacks
const roomParams = {
onPeerJoined: (room, participantList) => {
// room: Room
// participantList: string[]
console.log('New participants joined:', participantList);
participantList.forEach(participantID => {
const participant = room.participants.find(p => p.participantID === participantID);
if (participant) {
console.log(`- ${participant.name} (${participant.playerID})`);
}
});
},
onPeerLeft: (room, participantList) => {
// room: Room
// participantList: string[]
console.log('Participants left:', participantList);
},
onPeerConnected: (room, participantList) => {
// room: Room
// participantList: string[]
console.log('Participants connected:', participantList);
},
onPeerDisconnected: (room, participantList) => {
// room: Room
// participantList: string[]
console.log('Participants disconnected:', participantList);
}
};
Connection State Callbacks
const roomParams = {
onConnectedToRoom: (room) => {
// room: Room
console.log('Fully connected to room:', room.roomID);
// Start sending game data
},
onDisconnectedFromRoom: (room) => {
// room: Room
console.log('Disconnected from room:', room.roomID);
// Handle reconnection or return to lobby
}
};
Reconnection Callbacks
const roomParams = {
attemptingReconnect: () => {
console.log('Attempting to reconnect to room...');
// Show reconnection UI
},
reconnectSuccessful: () => {
console.log('Reconnection successful!');
// Hide reconnection UI, resume game
}
};
RTM Endless Room Callbacks
Endless room callbacks are identical to standard room callbacks but support dynamic player management.
const endlessParams = {
// Same callbacks as standard rooms
onRoomCreated: (status, room) => {
if (status) {
console.log('Endless room created:', room.roomID);
console.log('Max players:', room.max_players);
}
},
onPeerJoined: (room, participantList) => {
console.log('Players joined endless room:', participantList.length);
// Handle drop-in gameplay
},
onPeerLeft: (room, participantList) => {
console.log('Players left endless room:', participantList.length);
// Handle drop-out gameplay
}
};
Tournament Callbacks
Tournament Metadata Callback
MoitribeSDK('my-game-id', 'groupTournamentMeta', {}, (result) => {
// result: { success: boolean, tournaments?: any[], message?: string }
if (result.success && result.tournaments) {
result.tournaments.forEach(tournament => {
console.log(`Tournament: ${tournament.name}`);
});
} else {
console.error('Failed to load tournament metadata:', result.message);
}
});
Tournament Data Callback
MoitribeSDK('my-game-id', 'groupTournamentData', {
tournamentid: 'tournament-123'
}, (result) => {
// result: { success: boolean, tournament?: any, message?: string }
if (result.success && result.tournament) {
console.log('Tournament data:', result.tournament);
} else {
console.error('Failed to load tournament data:', result.message);
}
});
Tournament Join Callback
MoitribeSDK('my-game-id', 'groupTournamentJoin', {
tournamentid: 'tournament-123'
}, (result) => {
// result: { success: boolean, joined?: boolean, message?: string }
if (result.success && result.joined) {
console.log('Successfully joined tournament');
} else {
console.error('Failed to join tournament:', result.message);
}
});
Tournament Score Submission Callback
MoitribeSDK('my-game-id', 'groupTournamentScoreSubmit', {
tournamentid: 'tournament-123',
score: 2500
}, (result) => {
// result: { success: boolean, submitted?: boolean, message?: string }
if (result.success && result.submitted) {
console.log('Tournament score submitted successfully');
} else {
console.error('Score submission failed:', result.message);
}
});
Tournament Results Callback
MoitribeSDK('my-game-id', 'groupTournamentResults', {
tournamentid: 'tournament-123'
}, (result) => {
// result: { success: boolean, results?: any[], message?: string }
if (result.success && result.results) {
result.results.forEach((result, index) => {
console.log(`${index + 1}. ${result.playerName}: ${result.score}`);
});
} else {
console.error('Failed to load tournament results:', result.message);
}
});
Connection Callbacks
Global Connection State Callbacks
Used during SDK initialization for monitoring connection state.
MoitribeSDK('my-game-id', 'init', {
noui: true,
connectionCallbacks: {
onConnectionLost: (errorCode, errorMsg) => {
// errorCode: number
// errorMsg: string
console.error(`Connection lost (${errorCode}): ${errorMsg}`);
// Handle connection loss
},
onConnected: (isReconnect, URI) => {
// isReconnect: boolean
// URI: string
console.log(`Connected to ${URI} (reconnect: ${isReconnect})`);
},
onSuccessConnect: () => {
console.log('Connection successful');
},
onFailureConnect: () => {
console.error('Connection failed');
}
}
}, (result) => {
console.log('Init complete:', result);
});
Callback Best Practices
Error Handling
Always check the success status and handle errors appropriately.
function createSafeCallback(operation) {
return (result) => {
try {
if (result.success) {
operation(result);
} else {
console.error(`${operation.name} failed:`, result.message);
// Show user-friendly error message
showErrorToUser(result.message || 'Operation failed');
}
} catch (error) {
console.error('Callback error:', error);
}
};
}
// Usage
MoitribeSDK('my-game-id', 'submitscore', {
leaderboardid: 'high-scores',
score: 1500
}, createSafeCallback((result) => {
console.log('Score submitted with rank:', result.rank);
}));
Callback Chaining
For operations that depend on each other, chain callbacks properly.
// First authenticate, then submit score
MoitribeSDK('my-game-id', 'loginWithOtp', {
emailid: 'player@example.com',
otp: '123456'
}, (loginResult) => {
if (loginResult.success) {
// Now submit score
MoitribeSDK('my-game-id', 'submitscore', {
leaderboardid: 'high-scores',
score: 1500
}, (scoreResult) => {
if (scoreResult.success) {
console.log('Score submitted after login');
}
});
}
});
Cleanup Callbacks
When leaving rooms or cleaning up, ensure callbacks are properly handled.
let currentRoomCallbacks = null;
function createRoom() {
currentRoomCallbacks = {
onMessageReceived: handleMessage,
onPeerJoined: handlePeerJoined,
onLeftRoom: (status, roomID) => {
console.log('Left room, cleaning up');
currentRoomCallbacks = null;
}
};
MoitribeSDK('my-game-id', 'createstandardroom', currentRoomCallbacks, () => {});
}
function leaveRoom() {
if (currentRoomCallbacks) {
MoitribeSDK('my-game-id', 'leavestandardroom', {}, () => {
// Callbacks will be cleaned up in onLeftRoom
});
}
}
TypeScript Callback Types
Define proper types for better type safety.
interface ScoreSubmitResult {
success: boolean;
rank?: number;
message?: string;
}
interface LeaderboardScoresResult {
success: boolean;
scores?: LeaderboardScoreData[];
message?: string;
}
const handleScoreSubmit: CallbackFunction<ScoreSubmitResult> = (result) => {
if (result.success && result.rank) {
console.log(`Achieved rank: ${result.rank}`);
}
};
const handleScoresLoaded: CallbackFunction<LeaderboardScoresResult> = (result) => {
if (result.success && result.scores) {
result.scores.forEach(score => console.log(score.playerName));
}
};
Always implement error handling in callbacks to provide a smooth user experience and prevent silent failures.
Next Steps
- SDK Methods Reference - All available SDK methods
- Constants Reference - Message types and status codes
- Models Reference - Data structures and types