Be a Supporter!

Browse Sections


Newgrounds Wiki: Handling API Events

Since the Newgrounds API often has to communicate with the Newgrounds servers, most API commands won't finish immediately when you run them. The results only come from the server after a bit of time. Therefore, the API uses events to make it easy to listen for the results you're interested in.

For example, the first event that the API fires is API_CONNECTED. You can be listen for this even if you want to be sure that the API has connected, and the other commands are ready to be used. This is how you listen for this event:
import com.newgrounds.*;
API.addEventListener(APIEvent.API_CONNECTED, onAPIConnected);

function onAPIConnected(event:APIEvent):void { if(event.success) { trace("The Newgrounds API connected succesfully! You can now use the API features."); } else { trace("Unable to connect to the Newgrounds API. The error was: " + event.error); } }
Notice that we look at event.success to see if we connected properly. If a command fails, the API will still fire the event, but event.success will be false. It's always a good practice to check for success. If success is false, you can check event.error for a more specific error type.

All APIEvents are globally dispatched through the API class, and all different types of API events can be handled in this same way, simply by changing the event type you give to addEventListener. Here's an example of how you can listen for a medal unlock:
import com.newgrounds.*;
API.addEventListener(APIEvent.MEDAL_UNLOCKED, onMedalUnlocked);

function onMedalUnlocked(event:APIEvent):void { if(event.success) { var medal:Medal = Medal(event.data); trace("Medal was unlocked: " + medal.name); } else { trace("Medal unlock failed: " + event.error); } }
Notice that we accessed the medal that was unlocked by using event.data. If an event refers to a specific object, you can use event.data to access that object. For example, the data of a FILE_LOADED event will be the SaveFile object that was loaded.

The API class dispatches all API related events globally. Additionally, objects like Medals will also redispatch these events themselves. You have the option of listening to these objects for events, as well:
import com.newgrounds.*;

var medal:Medal = API.getMedal("Superman"); medal.addEventListener(APIEvent.MEDAL_UNLOCKED, onMedalUnlocked);

function onMedalUnlocked(event:APIEvent):void { if(event.success) { var medal:Medal = Medal(event.data); trace("Medal was unlocked: " + medal.name); } else { trace("Medal unlock failed: " + event.error); } }
In this case, our event handler will get called only when the Superman medal is unlocked. Listening to objects in this way can be helpful if you want more fine-grained control and only wish to listen to a specific object.