Events

The Events class is the heart of the BNMAPI.  It is used extensively to create decoupled event broadcasts between listeners and broadcasters.  That is, listeners may add themselves as listeners to a specific event without the broadcaster necessarily existing yet.

__/ REQUIREMENTS \__

ActionScript 3.0 (or later)

__/ IMPORTS \__

com.bnm.api.instances.ErrorBroadcast com.bnm.api.instances.Exception flash.events.StatusEvent flash.events.AsyncErrorEvent flash.external.* flash.net.* flash.system.*

__/ EXTENDS \__

com.bnm.api.JavaScript

__/ IMPLEMENTS \__

nothing

__/ NOTICE \__

©opyright 2008 Bay New Media.  All rights, as stipulated in the The MIT License, are reserved.

This ActionScript library is licensed and released under the MIT License (http://www.opensource.org/licenses/mit-license.php).  Please refer to the accompanying text file “license.txt”, which should be distributed with every package and version of this library, for information on usage, distribution, copying, and other important information.

Please visit http://www.baynewmedia.com/ or email con.nosp@m.tact@baynewm.nosp@m.edia.com for information, questions, concerns, or bug reports.

__/ NOTES \__

This class is commented using the NaturalDocs documentation system.  It is intended to be easily read both from the direct source code and from an adaptation that is generated as hyperlinked HTML.  The NaturalDocs specification used in this class’ documentation is version 1.35 though older versions may probably be used safely.  For more information, please visit: http://www.naturaldocs.org/

The BNMAPI is officially available (primary sources) on Source Forge (http://sourceforge.net/projects/bnmapi/), on the Bay New Media site (http;//www.baynewmedia.com/), on the PeaBee project site (http://www.peabee.com/), and through the Bay New Media SVM repository server (visit http://www.baynewmedia.com/ for more information).  Downloads from other sources may not be complete or up-to-date.

If you’re interested in joining the BNMAPI project in any capacity (development, testing, distribution, etc.), please visit us on Source Forge or the Bay New Media web site.

Summary
EventsThe Events class is the heart of the BNMAPI.
Variables
Events_nodeName(String) The name of the connection being used for this node.
Events_initialized(Boolean) Stores whether (TRUE) or not (FALSE) the event broadcasting system is initialized.
_eventCounter (number): Adds a unique number to each registered event so that there are no problemsarising from duplicate listeners.
events_listeners(Array) An array of listening objects.
Events_listeners
Events_connection(LocalConnection) Listening and broadcasting connection used for external events.
Events_nodes(Array) Array of external event nodes.
Events_JSsupported(Boolean) TRUE if the JavaScript event mechanism is available via the ExternalInterface class.
_currentExternalNodeIndex(int) The index of the current external node being accessed for a broadcast.
Functions
EventsConstructor method for the class.
broadcastBroadcasts an event to all listeners.
addListenerAdds a listener to the listener stack to be called whenever an event, denoted by the string message, is broadcast.
removeListenerRemoves a listener from the stack.
addExternalNodeAdds a node to the list of available nodes for external event calls via the LocalConnection object.
broadcastExternalEventBroadcasts an external event to all listening clients using the LocalConnection object.
broadcastJavaScriptEventBroadcasts an external event to all listening clients using the ExternalInterface object.
sendExternalEventSends an external event to a specific node using the LocalConnection object.
receiveExternalEventReceives external events from sending nodes via the LocalConnection object.
receiveJavaScriptEventReceives an event from a JavaScript event broadcast.
registerExternalEventsRegisters this class and the API with any other external event listeners/broadcasters.
onExternalEventStatusHandles StatusEvent events sent by the LocalConnection instance used for external broadcasts.
onExternalEventErrorHandles asynchronous error events raised by the LocalConnection instance used for external broadcasts.
registerExternalNodeAttempts to register a single external event node at a given node index.
deRegisterExternalNodeDe-registers an external node as a listener.
registerJavaScriptEventsRegisters a listening method within this class with the ExternalInterface class for invokation via JavaScript.
externalSecurityCheckMethod used for validity/security checking of URLs for LocalConnection connection attempts.

Variables

Events_nodeName

public static var Events_nodeName: String

(String) The name of the connection being used for this node.

Events_initialized

public static var Events_initialized: Boolean

(Boolean) Stores whether (TRUE) or not (FALSE) the event broadcasting system is initialized.  This static variable may be accessed directly by any etending class if required.  Typically, if the instance is not yet initialized, events simply won’t be broadcast.

_eventCounter (number): Adds a unique number to each registered event so that there are no problems

public static var _eventCounter: Number

arising from duplicate listeners.

events_listeners

(Array) An array of listening objects.

Events_listeners

public static var Events_listeners: Array

Events_connection

public static var Events_connection: LocalConnection

(LocalConnection) Listening and broadcasting connection used for external events.

Events_nodes

public static var Events_nodes: Array

(Array) Array of external event nodes.

Events_JSsupported

public static var Events_JSsupported: Boolean

(Boolean) TRUE if the JavaScript event mechanism is available via the ExternalInterface class.  Even though the API may be running in the browser, it may not be embedded within HTML and so JavaScript may not be available.  This is typically determined when attempting to register events at startup.

_currentExternalNodeIndex

private var _currentExternalNodeIndex: int

(int) The index of the current external node being accessed for a broadcast.  This is used for tracking which node has been removed when a StatusEvent of an error type is raised by the LocalConnection instance.

Functions

Events

public function Events ()

Constructor method for the class.

Parameters

initObj (object, optional): An object containing reciprocal properties to the class instance.  That is, each item in the object will be assigned to an existing or new item in the class instance. strict (boolean, optional): If TRUE, items in initObj must both exist and be of the same type as the reciprocal items in the class instance.  Any items not matching this criteria is discarded.

Returns

Events: A reference to the newly created class instance.

Broadcasts

nothing

Throws

nothing

Bubbles

no

See also

<init> <setDefaults>

broadcast

public function broadcast (eventObj: Object,
... args):Array

Broadcasts an event to all listeners.  This is used for all types of event broadcast including external, JavaScript, and internal.

Parameters eventObj (object, required): Generic object or class instance that contains the data to broadcast.  A broadcast object can contain the following properties:

event (String, required): The message to broadcast.  This must not be a blank string.  The name is free-form but it it is recommended that it be of the form “ObjectName.EVENT”.  For example, a load end event that is broadcast by the Loader class would send “Loader.LOADEND”.  This is the convention followed by the API.  Please refer to API documentation for a list of events and associated parameters that are available. message (String, optional): An optional parameter that is an alias for the “event” parameter.  This is included for legacy calls and is only used if the “event” parameter is omitted or NULL.  Otherwise this parameter is assumed to be a generic parameter intended for listeners. id (String, optional): An optional parameter that is a secondary alias for the “event” parameter.  This parameter is used as an event parameter only if “event” and “message” are not included, otherwise this is not interpreted by the broadcast controller. sender (untyped, optional): The sender of the object (usually ‘this’).  Used by listeners that listen only to specific objects.  If this parameter is not supplied, only listeners that are not listening to specific objects will receive the event.  For external events, the sender will usually be a string representation of the sending object.  LocalConnection events will send the name of the connection that is sending while JavaScript events will (typically) send the string “JavaScript”.  However, since JavaScript is intended as an external gateway for other developers, this may not always be the case.  For this reason, the ‘javascript’ property is set by the receiving method so that such calls may be identified. external (boolean, optional): Supplied by the listener for external events (LocalConnection interface).  If set to FALSE, the event is not broadcast to external listeners thereby avoiding circular calls.  If TRUE or undefined, the event is broadcast externally.  Default is TRUE. javascript (boolean, optional): Supplied by the listener for external events (ExternalInterface interface).  If set to FALSE, the event is not broadcast to external JavaScript listeners thereby avoiding circular calls.  If TRUE or undefined, the event is broadcast externally to JavaScript.  Default is TRUE.

Returns Array: An array of all of the registered listeners for this broadcast.  If no listeners are registered or some error occurred, NULL is returned.

Broadcasts

All Events: This is the main event broadcasting method and therefore all events will come through it.

Throws

nothing

Bubbles

no

addListener

public function addListener(listener: Function,
event: String,
... args):Object

Adds a listener to the listener stack to be called whenever an event, denoted by the string message, is broadcast.  More than one listener may be added to the listener stack.  When a message is broadcast, the methods in the listener stack are invoked in the order in which they were added.  Note that this was changed from “addEventListener” in the ActionScript 2.0 version due to disallowed and incompatible overrides.

Parameters listener (Function, required): The function to call whenever the message specified in ‘message’ is broadcast. event (string, optional): The event to listen to.  This is a generic message and each implementation may be different.  The Broadcast class is only responsible for storing and diseminating messages, not for specifying their content.  Omitting the message (or passing an empty string) will cause the ‘listener’ method to receive all messages. context (untyped, optional): The context, or scope, in which to invoke the ‘listener’ method.  If not specified, all events of the type specified by the “event” string will be received, regardless of the sender. targetObject (untyped, optional): Defines a specific broadcast sender so that only messages originating from this object are listened to. oneTime (boolean, optional): Specifies whether or not this is a “one time” listener.  If TRUE, the listener will only be called one time from its accompanying event and then removed from the listener stack as if the <removeEventListener> method was invoked.  If FALSE, the listener must be removed manually.  Because the listener reference is kept in memory (until removed), the accompanying method will also not be disposed of by the garbage collector.  It is therefore advisable to use oneTime wherever possible. allowExternal (boolean, optional): Specifies whether or not to allow external events to count as valid broadcasters.  Any events broadcast via LocalConnection or JavaScript count as external events and it is sometimes not desired to allow interaction from these sources.  Setting this value to TRUE adds the listener as allowing external broadcasts.  A value FALSE will disable external broadcasts, even if all event parameters and the message match.

Returns Object: A reference to the event object created in the listener array.  If there was an error of some sort, NULL is returned.

Broadcasts

nothing

Throws

nothing

Bubbles

no

See also

removeListener <addExclusiveListener>

removeListener

public function removeListener(listener: Function,
msg: String,
... args):Boolean

Removes a listener from the stack.  By default, ff the listener is registered more than once for the same event, each one must be removed separately as this method will only remove the first instance it encounters.  However, this behaviour may be overriden with an extra parameter.  Note that this was changed from “removeEventListener” in the ActionScript 2.0 version due to disallowed and incompatible overrides.

Parameters

listener (function, required): A reference to the listening function. msg (string, required): The event message that the listener is listening for. targetObject (untyped, optional): Specifies a targetted object that is broadcasting events.  If a specific object is targetted when adding a listener, this object may also be included here to ensure that the proper event is removed.

Returns

boolean: TRUE if the listener was successfully removed, FALSE if ‘listener’ is not a function type or if no listener with the specified function was found.

Broadcasts

nothing

Thows

nothing

Bubbles

no

addExternalNode

public function addExternalNode (externalEvent: Object):void

Adds a node to the list of available nodes for external event calls via the LocalConnection object.

Parameters

externalEvent (object, required): An object containing information about the external node.  The following properties are required for proper functionality of the external event mechanism: nodeName (string, required): The string name of the node that is being registered.  The standard name is ‘_BNMAPI_eventNode#’ where # is the sequential number of the node being attempted.

Returns

nothing

Broadcasts

nothing

Throws

nothing

Bubbles

no

broadcastExternalEvent

public function broadcastExternalEvent (externalEvent: Object):void

Broadcasts an external event to all listening clients using the LocalConnection object.

Parameters

externalEvent (object, required): An object containing the properties of the external call.  The contents of the object are not strictly enforced but since they are intended to be received by a listening instance of this class, the following properties should be present:

Returns

nothing

Broadcasts

All External Events: This is the main method responsible for broadcasting all external (LocalConnection) events.

Throws

nothing

Bubbles

no

See also

sendExternalEvent receiveExternalEvent

broadcastJavaScriptEvent

public function broadcastJavaScriptEvent (externalEvent: Object):void

Broadcasts an external event to all listening clients using the ExternalInterface object.

Parameters

externalEvent (object, required): An object containing the properties of the external call.  The contents of the object are not strictly enforced and it is up to the specific JavaScript implementation to properly interpret the object properties.  Events broadcast from this API, however, will have the following properties:

Returns

nothing

Broadcasts

All JavaScript Events: This is the main method used for broadcasting all JavaScript events.  The method used (ExternalInterace, fscommand, getURL) is dependent on the class settings.

Throws

nothing

Bubbles

no

See also

receiveJavaScriptEvent

sendExternalEvent

public function sendExternalEvent (externalEvent: Object)

Sends an external event to a specific node using the LocalConnection object.

Parameters

externalEvent (object, required): An object containing the properties of the external call.  The contents of the object are not strictly enforced but since they are intended to be received by a listening instance of this class, the following properties should be present:

Returns

nothing

Broadcasts

All Targetted External Events: This is the main method responsible for broadcasting events to all specific event listening nodes.

Throws

nothing

Bubbles

no

See also

sendExternalEvent receiveExternalEvent

receiveExternalEvent

public function receiveExternalEvent (externalEvent: Object)

Receives external events from sending nodes via the LocalConnection object.  The event is then re-broadcast internally so that all internal listers receive it as though it was sent internally.

Parameters

externalEvent (object, required): A standard event object.  This object should be a native Flash object and have all of the required properties of an event object (see <broadcast> method).  A couple of properties (‘external’ and ‘javascript’) are implicitly set to FALSE to prevent rebroadcasting outside of the internal scope.

Returns

nothing

Broadcasts

All External-Originating Events: This is the main method used for re-broadcasting internally all events received externally via LocalConnection.

Throws

nothing

See also

broadcast

receiveJavaScriptEvent

public function receiveJavaScriptEvent(externalEvent: Object,
argsPackage: Array)

Receives an event from a JavaScript event broadcast.  To broadcast a method from JavaScript, a similar event object to that used in this class’ ‘receiveExternalEvent’ method must be constructed in order to properly propagate throughout the API.  For a sample of a JavaScript call to this method, see the header in this class.

Parameters

externalEvent (object, required): An object containing the properties of an external event.  This is typically constructed by the sender.  It should follow the object structure specified in the ‘broadcast’ method of this class. argsPackage (array, optional): A numbered array used to hold any extra parameters included in the calling JavaScript event.  Because the JavaScript “apply” method does not work exactly in the same way as internally in Flash, arguments cannot simply be passed in.  Instead they are collected into a numbered array and re-constructed into local parameters to mimick parameter ordering.  The argsPackage excludes the event object and includes only parameters starting at position 1.

Returns

nothing

Broadcasts

All JavaScript-Originating Events: This is the main method used for re-broadcasting internally any methods received from JavaScript.

Throws

nothing

Bubbles

no

registerExternalEvents

public function registerExternalEvents()

Registers this class and the API with any other external event listeners/broadcasters.  This is done by using attemtping connections on standard sequential connection names.  The standard name is ‘_BNMAPI_eventNode#’ where # is the sequential number of the node being attempted.  If the connection fails (connection already exists), it is assumed that the node exists and is added to the existing nodes list for message broadcasts.  If the node doesn’t exist, it is assumed that this instance can use the connection.  The valid connection name is then broadcast to all existing nodes to register itself with them.  This methodology allows for a decentralized structure where nodes may be added or removed from the external event chain withoout the need for a centralized server.  As such, an application may continue to function even if some non-vital module is removed.  The external event broadcasting system should be backwards compatible with the AS2.0 API except that nodes are limitted in number to 1024 or less.

Parameters

none

Broadcasts

Target Sub-Broadcasts: This method is used to register this API instance with any other external event nodes.  This is done through a special broadcast that targets specific nodes but not received (or structured) as a regular event.

Returns

nothing

Throws

com.bnm.api.Exception

Bubbles

no

See also

receiveExternalEvent

onExternalEventStatus

public function onExternalEventStatus(eventObj: StatusEvent)

Handles StatusEvent events sent by the LocalConnection instance used for external broadcasts.  This is broadcast by LocalConnection whenever the connection status changes (a message is sent, received, or an error occurs).

Parameters

eventObj (StatusEvent, required): A standard StatusEvent object.

Returns

nothing

Broadcasts

nothing

Throws

nothing

Bubbles

no

onExternalEventError

public function onExternalEventError(eventObj: AsyncErrorEvent)

Handles asynchronous error events raised by the LocalConnection instance used for external broadcasts.  This typically occurs if a listener is not yet created or something else went wrong when attempting to create the LocalConnection instance.

Parameters

eventObj (AsyncErrorEvent, required): A standard AsyncErrorEvent object.

Returns

nothing

Broadcasts

nothing

Throws

nothing

Bubbles

no

registerExternalNode

private function registerExternalNode (nodeNum: int):Boolean

Attempts to register a single external event node at a given node index.  This allows the registerExternalEvents method to run through numerous connection attempts without resorting to internally dealing with “try..catch” recursion (which causes many problems within the same block).

Parameters

nodeNum (integer, required): The external node number to attempt a connection on.  Although the number of loops is, in the registerExternalEvents method limitted to 1024, calling this method directly can be used to register at any node index within the integer range.

Returns

Boolean: TRUE if the external node was registered at this index, FALSE if the registration failed (usually because another node is already registered to this slot).

Broadcasts

nothing

Throws

nothing

Bubbles

no

See also

registerExternalEvents

deRegisterExternalNode

private function deRegisterExternalNode (nodeNum: int):void

De-registers an external node as a listener.  This is done automatically as a response to an error-level status report generated by the LocalConnection instance.

Parameters

nodeNum (integer, required): The external node index to remove from the listener/broadcast list/

Returns

nothing

Broadcasts

nothing

Throws

nothing

Bubbles

no

See also

registerExternalEvents

registerJavaScriptEvents

private function registerJavaScriptEvents()

Registers a listening method within this class with the ExternalInterface class for invokation via JavaScript.  This allows JavaScript to broadcast events throughout the API.  An associated include script is provided with the API that mimicks event broadcasting within JavaScript so that JavaScript components can easily communicate with Flash components.  Note that numerous Flash objects on a single web page cause known problems in the ExternalInterface class and therefore only one class should be enabled as the “base” JavaScript gateway.  Internal re-broadcasting is then done on all received messages so that all components still receive events even though they didn’t specifically reach all Flash components directly from JavaScript.  This issue may be addressed in future versions of Flash.

Parameters

none

Returns

nothing

Broadcasts

nothing

Throws

none

Bubbles

no

See also

receiveJavaScriptEvent

externalSecurityCheck

private function externalSecurityCheck(URL: String):Boolean

Method used for validity/security checking of URLs for LocalConnection connection attempts.  Since it is assumed that any number of nodes may attempt to connect at any time to this instance, TRUE is always returned (no security check is done).

Parameters

URL (string, required): This is the default parameter supplied to this metod by the LocalConnection object.  Currently this value is ignored but it may be used to check URLs for validity before allowing LocalConnection connections.

Returns

boolean: TRUE if the URL supplied is allowed to communicate using LocalConnection, FALSE otherwise.  Currently returns TRUE always.

Broadcasts

nothing

Throws

nothing

Bubbles

no

See also

registerExternalEvents

Provides extended JavaScript functionality for the BNMAPI above and beyond standard ExternalInterface functionality.
Manages the creation, destruction, and execution of thread instances.
public static var Events_nodeName: String
(String) The name of the connection being used for this node.
public static var Events_initialized: Boolean
(Boolean) Stores whether (TRUE) or not (FALSE) the event broadcasting system is initialized.
public static var _eventCounter: Number
arising from duplicate listeners.
public static var Events_listeners: Array
public static var Events_connection: LocalConnection
(LocalConnection) Listening and broadcasting connection used for external events.
public static var Events_nodes: Array
(Array) Array of external event nodes.
public static var Events_JSsupported: Boolean
(Boolean) TRUE if the JavaScript event mechanism is available via the ExternalInterface class.
private var _currentExternalNodeIndex: int
(int) The index of the current external node being accessed for a broadcast.
public function Events ()
Constructor method for the class.
public function broadcast (eventObj: Object,
... args):Array
Broadcasts an event to all listeners.
public function addListener(listener: Function,
event: String,
... args):Object
Adds a listener to the listener stack to be called whenever an event, denoted by the string message, is broadcast.
public function removeListener(listener: Function,
msg: String,
... args):Boolean
Removes a listener from the stack.
public function addExternalNode (externalEvent: Object):void
Adds a node to the list of available nodes for external event calls via the LocalConnection object.
public function broadcastExternalEvent (externalEvent: Object):void
Broadcasts an external event to all listening clients using the LocalConnection object.
public function broadcastJavaScriptEvent (externalEvent: Object):void
Broadcasts an external event to all listening clients using the ExternalInterface object.
public function sendExternalEvent (externalEvent: Object)
Sends an external event to a specific node using the LocalConnection object.
public function receiveExternalEvent (externalEvent: Object)
Receives external events from sending nodes via the LocalConnection object.
public function receiveJavaScriptEvent(externalEvent: Object,
argsPackage: Array)
Receives an event from a JavaScript event broadcast.
public function registerExternalEvents()
Registers this class and the API with any other external event listeners/broadcasters.
public function onExternalEventStatus(eventObj: StatusEvent)
Handles StatusEvent events sent by the LocalConnection instance used for external broadcasts.
public function onExternalEventError(eventObj: AsyncErrorEvent)
Handles asynchronous error events raised by the LocalConnection instance used for external broadcasts.
private function registerExternalNode (nodeNum: int):Boolean
Attempts to register a single external event node at a given node index.
private function deRegisterExternalNode (nodeNum: int):void
De-registers an external node as a listener.
private function registerJavaScriptEvents()
Registers a listening method within this class with the ExternalInterface class for invokation via JavaScript.
private function externalSecurityCheck(URL: String):Boolean
Method used for validity/security checking of URLs for LocalConnection connection attempts.