Triggering JavaScript events

There are two distinct types of events in modules:

  • JavaScript events which can be triggered from native code at any point, used for situations that aren't a direct response to an API method call.
  • Native events which are points in an application's execution that modules can hook into and execute their own code. For example modules can execute native code on application start, without having to use any JavaScript.

Quite frequently you'll want to handle a native event and trigger a corresponding JavaScript event. This section of the module docs will discuss the first type of event. If you're interested in the second type of event described, see Handling native events.

JavaScript

An example of listening for a JavaScript event is included in the inspector project:

forge.internal.addEventListener("alert.resume", function () {
    alert("Welcome back!");
});
  • Events are identified by a unique string, it is conventional to use the format module.eventName for this string as shown above.
  • The second parameter is a callback to be invoked whenever the event is triggered from native code: data can be passed in the first parameter to this callback.

Note: Your JavaScript will not be loaded in time to receive events very early in the lifecycle of the app, such as the onCreate event for Android. By the time your JavaScript is running, you can safely make API calls to your module.

Android

To trigger a JavaScript event from native Android code, the ForgeApp.event() method can be called at any point. For example:

ForgeApp.event("alert.resume", null);
  • The first parameter is the event identification string which is listened for in JavaScript.
  • The second is an optional object to pass back to JavaScript.

iOS

To trigger JavaScript events from native iOS code, use [ForgeApp event] at any point. For example:

[[ForgeApp sharedApp] event:@"alert.resume" withParam:nil];
  • The first parameter is the event identification string which is listened for in JavaScript.
  • The second is an optional object to pass back to JavaScript.