Using Namespaces to provide context in AS3

Monday, December 17th, 2007

Namespaces in ActionScript 3 are particularly useful for providing context in an application. They also provide an added clarity to APIs outside of the typical language specific access modifiers.

For instance, let’s say we have an application which requires slightly different behaviors depending on a specific type of user. If the user is a guest, the application need only display a fairly basic view, however, if the user is an administrator the application must display a slightly more complex view.

Based on the type of user we can deduce context and from this context we can provide a contextual namespace. The contextual namespace can then be utilized to invoke different methods with the same name on an object.

To help facilitate the management of a contextual namespace I have created a ContextNamespace API.

ContextNamespace is a Singleton class which can be utilized to set and retrieve a contextual namespace based on context. Additionally, ContextNamespace implements INamespaceManager which defines various convenience methods for retrieving information about a contextual namespace, comparing a Namespace against the contextual Namespace and comparing a URI against the contextual Namespace URI.

Below is a simple example which demonstrates how to utilize the ContextNamespace API.

The class below utilizes two custom namespaces; admin and guest. Two methods with the same name are defined in the Class, each of which is under a different namespace.

To utilize ContextNamespace to retrieve a reference to the current contextual Namespace is simple.

In the above code a local namespace is defined which references the current contextual namespace used by the application via ContextNamespace.instance.getNamespace(). The local reference is then used to identify the correct namespace from which methods are to be invoked.

For additional examples which demonstrate how ContextNamespace can be utilized to provide a globally accessible reference to a namespace, view the ASDocs.


{ Comments are closed! }