The HTML DOM provides a very powerful event model in which DOM elements publish events (e.g., click, load, resize, etc.) and JavaScript code subscribed to those events is triggered and executed when those events occur. Mojo provides a very similar event model for use in webOS applications.
There are three unique event types in Mojo that support different parts of the webOS UI system:
- System UI events (e.g. drag, flick, hold)
- Widget events (e.g. listTap, propertyChange)
- Application UI events: (e.g. scrollStarting, stageActivate, stageDeactivate)
The full list of event object properties for Mojo.Event has not yet been released publicly, but you can find a list of the elements revealed so far over at our Mojo API reference. You can also define custom events in Mojo using Mojo.Event.make() (although Palm has not yet revealed exactly how).
Listening for events
When an event occurs, code "listening" for that event is notified. There are three ways to subscribe to events on any DOM element:
- Mojo.Event.listen() or this.controller.listen()
- .addEventListener()
- observe()
Mojo.Event.listen() was created in case there are issues with addEventListener or the observe() method (a Prototype framework method), but Palm suggests that these methods are pretty much equivalent and that "at this point", all work equally well in Mojo.
Note that Prototype and getElementByID don't work across multiple stages, so for multi-stage apps you must use this.controller.listen() or this.controller.get() to pass or retrieve an element by DOM ID.
In addition to listening for events that are triggered based on user input, you can also propagate events to event handlers programmatically using Mojo.Event.send(). For example, this would enable you to trigger a button click event without a user actually tapping a button.
Example
Click here to see an example of how to subscribe to events using Mojo.Event.listen() and this.controller.listen().
Removing Listeners for Events
To stop listening for an event, use one of three methods (whichever matches your event listener setup call):
- Mojo.Event.stopListening() or this.controller.stopListening()
- .removeEventListener()
- stopObserving()
Using Events with Widgets
Many widgets are preconfigured to dispatch events, usually to the widget's element (the div with the x-mojo-element attribute). Palm says a complete list of the events dispatched by each widget will be provided with the SDK. In the meantime check out this example of Event listening on a widget, as well as other examples in our UI widget list.
This article is the first of many daily programming-related webOS articles. Grab the RSS feed to stay in the know.
Much of the information in this article was presented in Chapter 3 of Palm webOS by Mitch Allen.