Thư viện tri thức trực tuyến
Kho tài liệu với 50,000+ tài liệu học thuật
© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

Tài liệu đang bị lỗi
File tài liệu này hiện đang bị hỏng, chúng tôi đang cố gắng khắc phục.
O’Reilly Programming Flex 2 phần 3 pptx
Nội dung xem thử
Mô tả chi tiết
Variables and Properties | 71
You can access specific elements of the array using array access notation. The following example retrieves the first element from the array (ActionScript arrays are 0-
indexed) and displays it in the console (again, if you are debugging the application):
trace(book[0]);
You can also assign values to elements using array access notation, as follows:
book[2] = "Web Services Essentials";
Arrays are objects in ActionScript, and they have methods and properties like most
objects. It’s beyond the scope of this book to delve into the Array API in depth. However, of the Array API, the length property and push( ) method are the most commonly used. The length property returns the number of elements in the array, and it
is commonly used with a for statement to loop through all the elements of an array.
The push( ) method allows you to append elements to an array.
ActionScript arrays are not strongly typed. That means you can store any sort of data
in an array, even mixed types. Theoretically, you could store numbers, strings, dates,
and even other arrays in an array.
ActionScript does not have any formal hashmaps or similar types. ActionScript does
have an Object type, which is the most basic of all object types. Unlike the majority
of ActionScript classes the Object class is dynamic, which means you can add arbitrary properties to Object instances. Although it is generally better to write data
model classes than to store data in Object instances using arbitrary properties, there
are cases when it is useful to use an Object instance as a hashmap/associative array.
The following example creates an Object instance and assigns several keys and
values:
var authorsByBook:Object = new Object( );
authorsByBook["Programming Flex 2"] = "Chafic Kazoun,Joey Lott";
authorsByBook["ActionScript 3.0 Cookbook"] = "Joey Lott,Keith Peters,Darron Schall";
Objects
Objects are composites of state and functionality that you can use as elements within
ActionScript code. There are potentially an infinite range of object types, including
those from the built-in Flash Player types to Flex framework types to custom types.
An object is an instance of a class, which is a blueprint of sorts. Although there are
other mechanisms for creating objects, the most common is to use a new statement
with a constructor. The constructor for a class is a special function that shares the
same name as the class. For example, the constructor for the Array class is called
Array. Like any other functions a constructor may or may not expect parameters.
The only way to know whether a particular constructor expects parameters is to consult the API documentation. However, unlike most functions, a constructor must be
used as part of a new statement, and it always creates a new instance of the class. The
following example creates a new array using a new statement:
var books:Array = new Array( );
72 | Chapter 4: ActionScript
Objects may have properties and methods depending on the type. Properties are
essentially variables associated with an object, and methods are essentially functions
associated with the object. You can reference properties and methods of an object in
ActionScript using dot-syntax. Dot-syntax uses a dot between the name of the object
and the property of the method. The following example uses dot-syntax to call the
push( ) method of the array object (the push( ) method appends the value as an array
element):
books.push("Programming Flex 2");
The next example uses dot-syntax to reference the length property of the array
object:
trace(books.length);
Inheritance
You can create new classes (called subclasses) that inherit from existing classes
(called superclasses). You achieve this using the extends keyword when declaring the
class. The extends keyword should follow the class name and be followed by the
class from which you want to inherit. The following defines class B, so it inherits
from a fictional class, A:
package com.example {
import com.example.A;
public class B extends A {
}
}
ActionScript 3.0 allows a class to inherit from just one superclass. The subclass
inherits the entire implementation of the superclass, but it can access only properties
and methods declared as public or protected. Properties that are declared as private
and methods are never accessible outside a class—not even to subclasses. Classes in
the same package can access properties declared as internal. Consider the class A
and class B example, if A is defined as follows:
package com.example {
public class A {
private var _one:String;
protected var _two:String;
public function A( ) {
initialize( );
}
private function initialize( ):void {
_one = "one";
_two = "two";
}
public function run( ):void {
trace("A");
}
}
}
Interfaces | 73
In this example, B (which is defined as a subclass of A) can access _two and run( ), but
it cannot access _one or initialize( ).
If a subclass wants to create its own implementation for a method that it inherits
from a superclass, it can do so by overriding it. Normally, a subclass blindly inherits
all of the superclass implementation. However, when you override a method, you tell
the subclass that it should disregard the inherited implementation and use the overridden implementation instead. To override a method, you must use the override
keyword in the method declaration; the following overrides the run( ) method:
package com.example {
import com.example.A;
public class B extends A {
override public function run( ):void {
trace("B");
}
}
}
When a subclass overrides a superclass method, the subclass method’s signature
must be identical to the superclass method’s signature, i.e., the parameters, return
type, and access modifier must be the same.
Interfaces
ActionScript 3.0 also allows you to define interfaces. Interfaces allow you to separate
the interface from the implementation, which enables greater application flexibility.
Much of what you learned about declaring classes applies to declaring interfaces as
well. In fact, it’s easier to list the differences:
• Interfaces use the interface keyword rather than the class keyword.
• Interfaces cannot declare properties.
• Interface methods declare the method signature but not the implementation.
• Interfaces declare only the public interface for implementing classes, and therefore method signature declarations do not allow for modifiers.
By convention, interface names start with an uppercase I. The following is an example of an interface:
package com.example {
public interface IExample {
function a( ):String;
function b(one:String, two:uint):void;
}
}
In the preceding example, interface says that any implementing class must declare
methods a( ) and b( ) using the specified signatures.
74 | Chapter 4: ActionScript
You can declare a class so that it implements an interface using the implements keyword, following the class name or following the superclass name if the class extends
a superclass. The following example implements IExample:
package com.example {
import com.example.IExample;
public class Example implements IExample {
public function Example( ) {
}
public function a( ):String {
return "a";
}
public function b(one:String, two:uint):void {
trace(one + " " + two);
}
}
}
When a class implements an interface, the compiler verifies that it implements all the
required methods. If it doesn’t, the compiler throws an error. A class can implement
methods beyond those specified by an interface, but it must always implement at
least those methods. A class can also implement more than one interface with a
comma-delimited list of interfaces following the implements keyword.
Handling Events
ActionScript 3.0 and the Flex framework use events to notify and receive notification
when things occur. Events occur in response to the user (for example, the user clicks
on something), time (timer events), and asynchronous messaging (such as remote
procedure calls). Regardless of the cause of an event, nearly all ActionScript events
use the same event model.
In MXML (Chapter 3), you saw how to use event handler attributes. In ActionScript, you can handle events by registering listeners. A listener is a function or
method that should receive notifications when an event is dispatched. For example,
you can register a method to receive a notification when the user clicks a button.
You need at least two elements to register a listener: an object that dispatches events,
and a function that listens for events. Objects capable of dispatching events either
extend the flash.events.EventDispatcher class or implement the flash.events.
IEventDispatcher interface. When an object can dispatch events, it has a public
addEventListener( ) method that requires at least two parameters; the name of the
event for which you want to listen and the function/method that should listen for the
event:
object.addEventListener("eventName", listenerFunction);
In most cases, the event names are stored in constants of the corresponding event
type class. For example, the click event name is stored in the MouseEvent.CLICK
constant.
Handling Events | 75
The listener function must expect one parameter of type mx.events.Event or the relevant subclass of Event. For example, if the object dispatches an event of type
MouseEvent, the listener should accept a MouseEvent parameter. The event parameter
contains information about the event that occurred, including a reference to the
object dispatching the event (the target property of the event object) and the object
that most recently bubbled (relayed) the event (the currentTarget property). (In
many cases, the target and currentTarget properties reference the same object.) The
following example adds an event listener using ActionScript, and when the user
clicks the button, the listener displays the event object in an alert dialog box:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
initialize="initializeHandler(event)">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
private function initializeHandler(event:Event):void {
button.addEventListener(MouseEvent.CLICK, clickHandler);
}
private function clickHandler(event:MouseEvent):void {
Alert.show(event.toString( ));
}
]]>
</mx:Script>
<mx:Button id="button" />
</mx:Application>
You can also unregister an event listener using the removeEventListener( ) method.
This method requires the same parameters as addEventListener( ). The method
unregisters the specified listener function as a listener for the specified event. It is
extremely important that you remove event listeners when they are no longer necessary. This includes all cases where you want to remove from memory the object listening for the events. Flash Player will not garbage-collect an object if there are any
references to it still in memory. That means that even if an object is no longer used
anywhere in the application, except for a reference held by an event dispatcher, it
will not be garbage-collected.
The following example removes the event listener added in the previous example:
button.removeEventListener(MouseEvent.CLICK, onClick);