Listening to SDK events
You can subscribe to events broadcasted by the SDK when certain things happen. Doing so enables you to react to some events without having to continously poll.
To do so, call on()
to add an event listener. The arguments are:
- The event name
- A callback. The first argument will always be the api, other arguments depend on the event you're listening to.
batchSDK(api => {
api.on("event_name", (api, parameter) => {
// Do something with the parameter.
})
})
This documentation covers the most commonly used events. The full list of available events can be found here.
Broadcasted events
Subscription Changed
The subscriptionChanged
event is fired whenever the user push subscription changes. It gives a single parameter, which is the new subscription.
For example, you can do something when the user accepted the notification permission and subscription succeeded:
batchSDK(api => {
api.on("subscriptionChanged", (api, subscription) => {
if (subscription.subscribed) {
// The user has subscribed to notifications
// ...
}
})
})
Note: This event can be fired even without user action. Do not make the assumption that it will only be fired once: you may want to add a way to execute the callback only once using localstorage.
UI Ready
The uiReady
event is fired whenever Batch is ready to display UI.
For example, you can do something when Batch is ready and fully initialized to display your custom UI.
batchSDK(api => {
api.on("uiReady", (api) => {
// Show our hidden optin prompt
// document.querySelector("#my-push-optin-prompt").style.display = "initial";
})
})