close

Вход

Забыли?

вход по аккаунту

?

Flex+Questions

код для вставкиСкачать
1.How did you implement Abstraction class in flex?
package com.joshtynjala.abstract
{
import flash.errors.IllegalOperationError;
public class MyAbstractType
{
public function MyAbstractType(self:MyAbstractType)
{
if(self != this)
{
//only a subclass can pass a valid reference to self
throw new IllegalOperationError("Abstract class did not receive reference to
self. MyAbstractType cannot be instantiated directly.");
}
}
}
} package com.joshtynjala.abstract
{
public class MyConcreteType extends MyAbstractType
{
public function MyConcreteType()
{
//pass "this" to clear the abstract check
super(this);
}
}
} 2.Why we need Abstraction class rather than using Interface?
3.What is Singleton Pattern?
4.How will you implement Singleton Patten?
package
{
public final class Singleton
{
private static var _instance:Singleton = new Singleton();
public function Singleton()
{
if (_instance != null)
{
throw new Error("Singleton can only be accessed through Singleton.instance");
}
}
public static function get instance():Singleton
{
return _instance;
}
}
}
5.Private constructor is not possible in Flex? True ( It is possible in AS2 not in AS3)
6.Which framework did u implement in your project?
7.Explain about Project.
8.Have you created Custom Components
9.Have you modified the properties of existing components
10.How you can connect database from flex.
11.Which type of data transfers you are using in your project.
12.What made you to have custom component in project?
13. How will implement Iterator in Flex?
HasNext and Next are key function. Write a class and have a constructor (array: array),
and write two function HasNext and Next. HasNext will return Boolean value if
array.length is not matched index. Next will increment your index.
14. Type Introspection?
Type introspection enables you to look into elements of a class at runtime. The best way
to do this is to use the introspection API in AS3 - specifically the
flash.utils.describeType
class. The describeType()
method produces an XML object
that describes the object passed to it.
Note that only public methods are described using introspection. The private
methodThree()
method is invisible to the introspection API. A method
tag describes all
publicly declared methods. The declaredBy
attribute specifies the class that defined the
method.
15. Find Abstract Class and Abstract method in runtime? Using introspection to achieve this
package com.
as3dp
.
utils
{
import
flash.
utils
.
describeType
;
import
flash.
utils
.
getQualifiedClassName
;
import
flash.
errors
.
IllegalOperationError
;
public
class
RuntimeCheck {
/** * Runtime checks for abstract classes and methods
* Checks if callee is a subclass and has defined indicated methods.
* Should normally be called from the constructor of the abstract class.
*
* Note: Abstract method checks only work for public functions
* * @param instance calling object (the 'this' keyword)
* @param abstractClass the class name of the abstract class * @param abstractMethodList array of strings indicating the method names
* of abstract methods
* @exception IllegalOperationError if abstract class has not been subclassed or
* indicated methods have not been defined in subclass
* @author Chandima Cumaranatunge
* @version 0.1
*
* Usage:
* public class AbstractClass {
* public function AbstractClass() {
* RuntimeCheck.abstractClass(this, AbstractClass, ['abstractMethodOne',
'abstractMethodTwo']);
* }
* public function abstractMethodOne():void {}
* public function abstractMethodTwo():void {}
* }
*/
public
static
function
abstractClass
(
instance:
Object
, abstractClass:
Class
,
abstractMethodList:
Array
= null
)
:
void
{
var
instanceClassName = getQualifiedClassName
(
instance
)
;
if
(
instance.
constructor
=== abstractClass
)
{
throw
new
IllegalOperationError
(
"Abstract class '"
+ instanceClassName + "'
must be subclassed and not instantiated."
)
;
}
else
{
var
description:
XML
= describeType
(
instance
)
;
//trace(description);
for
each (
var
fnName:
String
in
abstractMethodList
)
{
var
overridenFlag:
Boolean
= false
;
for
(
var
pname:
String
in
description.
method
)
{
if
(
description.
method
.
@
name
[
pname
]
.
toString
()
== fnName
)
{
overridenFlag = (
description.
method
.
@
declaredBy
[
pname
]
.
toString
()
=== instanceClassName
)
;
}
}
if
(!
overridenFlag
)
{
throw
new
IllegalOperationError
(
"Abstract method '"
+ fnName + "' must
be overridden and implemented in subclass."
)
;
}
}
}
}
}
}
Tip: Not only does Flex enable skinning via images and precompiled Flash assets, you
also have the capability to do runtime vector drawing.
Tip: Whether written in MXML or ActionScript, all Flex components are classes. At
compile time, MXML is precompiled to ActionScript classes, which are then
compiled into the swf file format.
Encapsulation Advantage
Proper encapsulation helps to ensure that your code is easily read and
maintained. Adding/removing properties from a class instance should take place
within the class definition, not spread throughout the codebase.
Inheritance
When a class inherits from a base class, the new class can utilize public and protected
properties and methods from the base class.
Polymorphism
In Flex & ActionScript, polymorphism is achieved using Interfaces.
Static Methods and Variables
Static properties do not require a class instantiation to be used. You can access
a static property or method directly from the class definition.
– Alert.show( MyClass.myStaticVariable )
• Rather than
– Alert.show( new MyClass().myStaticVariable );
_ Since static properties and methods do not require class instatiation, they
require less memory and are less resource intensive.
Get and Set
The Benefits of Getters and Setters
_ Get/Set functions are extremely helpful for two reasons:
1. They can be overridden in derived classes. All classes that are derived from the base
class can extend or complely override the behavior of the get/set methods to suit the
needs of the derived class.
override public function set myValue (value:Number):void { …
2. They enable sequential code execution when accessed.
public function set myValue (value:Number):void
{
_myValue = value;
numSets ++;
myFunction();
}
– In this example, every time the value is set, the numSets Number is incremented, and
the
myFunction() function is executed. This also enables you to write cleaner and simpler
code. The
following would trigger this method:
myValue = 123;
Custom Component in Action Script
You can also create advanced ActionScript components. Advanced ActionScript
components might have one of the following requirements:
■ Modify the appearance of a control or the layout functionality of a container
■ Encapsulate one or more components into a composite component
■ Subclass UIComponent to create components
For information on creating advanced ActionScript
Meta Tag
Metadata tags provide information to the Flex compiler that describe how your
components
are used in a Flex application.
Flex compiler needs to know about new event introduced in Custom component.
[Event(name="enableChanged", type=flash.events.Event)] should go into
<mx:metadata> not in <mx:script>
If you omit the [Event] metadata tag from your class definition, Flex issues a syntax
error. when it compiles your MXML file. The error message indicates that Flex does not
recognize the enableChanged property.
The Flex compiler recognizes component metadata statements in your ActionScript class
files
and MXML files. The metadata tags define component attributes, data binding properties,
events, and other properties of the component. Flex interprets these statements during
compilation; they are never interpreted during run time.
Example:
[Event(name="enableChange", type=flash.events.Event)]
public class ModalText extends TextArea {
...
// Define class properties/methods
private var _enableTA:Boolean;
// Add the [Inspectable] metadata tag before the individual property.
[Inspectable(defaultValue="false")]
public function set enableTA(val:Boolean):void {
_enableTA = val;
this.enabled = val;
// Define event object, initialize it, then dispatch it.
var eventObj:Event = new Event("enableChange");
dispatchEvent(eventObj);
}
}
A key difference between the <mx:Metadata> and <mx:Script> tags is that text within the
<mx:Metadata> tag is inserted before the generated class declaration, but text within
<mx:Script> tag is inserted in the body of the generated class declaration. Therefore,
metadata tags like [Event] and [Effect] must go in an <mx:Metadata> tag, but the
[Bindable] and [Embed] metadata tags must go in an <mx:Script> tag.
ArrayElementType metadata tag
When you define an Array variable in ActionScript, you specify Array as the data type of
the
variable. However, you cannot specify the data type of the elements of the Array.
To allow the Flex MXML compiler to perform type checking on Array elements, you can
use
the [ArrayElementType] metadata tag to specify the allowed data type of the Array
elements, as the following example shows:
public class MyTypedArrayComponent extends VBox {
[ArrayElementType("String")]
public var newStringProperty:Array;
[ArrayElementType("Number")]
public var newNumberProperty:Array;
Bindable metadata tag
When a property is the source of a data binding expression, Flex automatically copies the
value of the source property to any destination property when the source property
changes. To signal to Flex to perform the copy, you must use the [Bindable] metadata tag
to register the property with Flex, and the source property must dispatch an event. The [Bindable] metadata tag has the following syntax:
[Bindable]
[Bindable(event="
eventname
")]
If you omit the event name, Flex automatically creates an event named propertyChange.
Note:
When you use the [Bindable] metadata tag before a public class definition, it only
applies to public properties; it does not apply to private or protected properties, or to
properties defined in any other namespace. You must insert the [Bindable] metadata tag
before a nonpublic property to make it usable as the source for a data binding expression.
■ Before a public, protected, or private property defined by a getter or setter method. You
must define both a setter and a getter method to use the [Bindable] tag with the property.
If you define just a setter method, you create a write-only property that you cannot use as
the source of a data-binding expression. If you define just a getter method, you create a
read-only property that you can use as the source of a data-binding expression without
inserting the [Bindable] metadata tag. This is similar to the way that you can use a
variable, defined by using the const keyword, as the source for a data binding expression.
Example : with Getter and Setter
private var _maxFontSize:Number = 15;
[Bindable(event="maxFontSizeChanged")]
// Define public getter method.
public function get maxFontSize():Number {
return _maxFontSize;
}
// Define public setter method.
public function set maxFontSize(value:Number):void {
if (value <= 30) {
_maxFontSize = value;
} else _maxFontSize = 30;
// Create event object.
var eventObj:Event = new Event("maxFontSizeChanged");
dispatchEvent(eventObj);
}
Note: You cannot use the [Bindable] metadata tag with a static variable. If you do,
the compiler
issues an error.
The [DefaultProperty] metadata tag defines the name of the default property of the
component when you use the component in an MXML file.
Event metadata tag
Use the [Event] metadata tag to define the MXML property for an event and the data type
of the event object that a component emits. You insert the [Event] metadata tag before the
class definition in an ActionScript file, or in the <mx:Metadata> block in an MXML file.
The [Inspectable] metadata tag must immediately precede the property’s variable
declaration or the setter and getter methods to be bound to that property.
NonCommittingChangeEvent metadata tag
The [NonCommittingChangeEvent] metadata tag identifies an event as an interim trigger,
which means that the event should not invoke Flex data validators on the property. You
use this tag for properties that might change often, but which you do not want to validate
on every change.
An example of this is if you tied a validator to the text property of a TextInput control.
The text property changes on every keystroke, but you do not want to validate the
property until the user presses the Enter key or changes focus away from the field. The
NonCommittingChangeEvent tag lets you dispatch a change event, but that does not
trigger validation.
Ex: The component dispatches the change event every time the user
enters a keystroke, but the change event does not trigger data binding or data validators.
When the user completes data entry, by pressing the Enter key, the component broadcasts
the valueCommit event to trigger any data bindings and data validators:
[Event(name="change", type="flash.events.Event")]
class MyText extends UIComponent {
...
[Bindable(event="valueCommit")]
[NonCommittingChangeEvent("change")]
function get text():String {
return getText();
}
function set text(t):void {
setText(t);
// Dispatch events.
}
}
Note: You cannot define a type selector in an MXML component. If you define a type
selector, a compiler error occurs.
XML Binding in DataGrid
------datagridXML.mxml------
<?xml version=
"1.0"
encoding=
"utf-8"
?>
<mx:Application xmlns:mx=
"
http://www.macromedia.com/2003/mxml
"
backgroundColor=
"#FFFFFF"
verticalGap=
"0"
initialize=
"myHTTPDetail.send()"
>
<mx:HTTPService id=
"myHTTPDetail"
showBusyCursor=
"true"
method=
"GET"
url=
"xmlService.cfm"
>
</mx:HTTPService>
<mx:DataGrid id=
"orderGrid"
dataProvider=
"{mx.utils.ArrayUtil.toArray(myHTTPDetail.result.employees.employ
ee)}"
width=
"375"
>
<mx:columns>
<mx:Array>
<mx:DataGridColumn columnName=
"id"
headerText=
"Id"
width=
"40"
/>
<mx:DataGridColumn columnName=
"name"
headerText=
"Name"
width=
"115"
/>
<mx:DataGridColumn columnName=
"title"
headerText=
"Description"
width=
"130"
/>
<mx:DataGridColumn columnName=
"phone"
headerText=
"Price"
/>
</mx:Array>
</mx:columns>
</mx:DataGrid>
</mx:Application>
Binding Complex XML to a DataGrid in Flex
The datagrid in Flex works very well with flat XML. For example if you have the
following XML it is very simple to bind it to a DataGrid.
<mx:Model id=
"thePersonModel"
>
<name>
Brandon
</name>
<age>
30
</age>
<address>
19 foobar
</address>
</mx:Model>
<mx:DataGrid id=
"myDataGrid"
dataProvider=
"{mx.utils.ArrayUtil.toArray(thePersonModel)}"
/>
But what if you have a more complex XML packet that you need to bind to a
DataGrid? <mx:Model id=
"thePersonModel"
>
<name>
Brandon
</name>
<age>
30
</age>
<address>
<street>
foobar
</street>
<number>
19
</number>
</address>
</mx:Model>
<mx:DataGrid id=
"myDataGrid"
dataProvider=
"{mx.utils.ArrayUtil.toArray(thePersonModel)}"
/>
In the above code the name and age will bind appropriately but the addess column
will show [object Object]
instead of the value of street and number. There is an easy
workaround to display the values of complex XML using the labelFunction from the
<mx:DataGridColumn> tag. When we call the labelFunction tag the dataprovider gets
passed to the function and we can grab any value from the dataprovider. The
following code shows how this works
<?xml version=
"1.0"
encoding=
"utf-8"
?>
<mx:Application xmlns:mx=
"
http://www.macromedia.com/2003/mxml
"
width=
"600"
height=
"450"
>
<mx:Script>
<![CDATA[ function myLabelFunc(item):String {
if (item.address.number==undefined)
{return null;}
else
{return item.address.number + " "
+ item.address.street;}
}
]]>
</mx:Script>
<mx:Model id=
"thePersonModel"
>
<name>
Brandon
</name>
<age>
30
</age>
<address>
<street>
foobar
</street>
<number>
19
</number>
</address>
</mx:Model>
<mx:DataGrid id=
"myDataGrid2"
dataProvider=
"{mx.utils.ArrayUtil.toArray(thePersonModel)}"
>
<mx:columns>
<mx:Array>
<mx:DataGridColumn columnName=
"name"
headerText=
"Name"
/>
<mx:DataGridColumn columnName=
"age"
headerText=
"Age"
/>
<mx:DataGridColumn headerText=
"Address"
labelFunction=
"myLabelFunc"
/>
</mx:Array>
</mx:columns>
</mx:DataGrid>
</mx:Application>
Adding and Deleting from Data Grid:
public
function
addPerson():
void
{
ac.addItem({first:firstInput.text, last:lastInput.text,
email:emailInput.text});
clearInputs();
}
// Remove a person from the ArrayCollection.
public
function
removePerson():
void
{
// Make sure an item is selected.
if
(dg.selectedIndex >= 0) {
ac.removeItemAt(dg.selectedIndex);
}
Adding Dynamically column in Data Grid:
<mx:Script>
<![CDATA[
import mx.controls.dataGridClasses.DataGridColumn;
private function addDataGridColumn(dataField:String):void {
var dgc:DataGridColumn = new DataGridColumn(dataField);
var cols:Array = dataGrid.columns;
cols.push(dgc);
dataGrid.columns = cols;
}
private function init():void {
addDataGridColumn("col4");
}
]]>
</mx:Script>
Custom Components
Note:
custom versions of nonvisual components, such as validators, formatters, and effects
Note:
You cannot override an inherited property defined by a variable, but you can override a
property defined by setter and getter methods. You can reset the value of an inherited
property defined by a variable. You typically reset it in the constructor of the subclass for
an ActionScript component, or in an event handler for an MXML component because
MXML components cannot define a constructor.
Decisions to create MXML and Action Script components.
Some basic guidelines include the following:
■ MXML components and ActionScript components both define new ActionScript
classes.
■ Almost anything that you can do in a custom ActionScript custom component, you can
also do in a custom MXML component. However, for simple components, such as
components that modify the behavior of an existing component or add a basic feature to
an existing component, it is simpler and faster to create them in MXML.
■ When your new component is a composite component that contains other components,
and you can express the positions and sizes of those other components using one of the
Flex layout containers, you should use MXML to define your component.
■ To modify the behavior of the component, such as the way a container lays out its
children, use ActionScript.
■ To create a visual component by creating a subclass from UIComponent, use
ActionScript.
■ To create a nonvisual component, such as a formatter, validator, or effect, use
ActionScript.
■ To add logging support to your control, use ActionScript.
RSL File
One way to reduce the size of your application’s SWF file is by externalizing shared
assets intostand-alone files that can be separately downloaded and cached on the client.
These shared assets are loaded by any number of applications at run time, but only need
to be transferred to the client once. These shared files are known as Runtime Shared
Libraries or RSLs.

ActionScript provides flow control and object manipulation features
that are not available in MXML.

There is a distinct difference between including and importing in ActionScript.
Including is

copying lines of code from one ActionScript file into another. Files that you
include must be

located relative to the file performing the include, or use an absolute path.
Importing is adding

a reference to a class file or package so that you can access objects and properties
defined by

external classes.
Getter and Setter
you can perform the following actions:
■ Inspect and validate any data written to the property on a write
■ Trigger events that are associated with the property when the property changes
■ Calculate a return value on a read
■ Allow a child class to override
Using an event object
When a Flex component dispatches an event, it creates an event object, where the
propertiesof the event object contain information describing the event. An event listener
takes this event object as an argument and accesses the properties of the object to
determine information about the event.
The base class for all event objects is the flash.events.Event class. All event objects are
instances of the Event class, or instances of a subclass of the Event class.
Dispatching Custom Events
To dispatch a new event from your custom component, you must do the following:
1. (Optional) Create a subclass from the flash.events.Event class to create an event class
that
describes the event object. 2. (Optional) Use the [Event] metadata tag to make the event public so that the MXML
compiler recognizes it. 3.
Dispatch the event using the dispatchEvent() method.
Meta Data Tag
Metadata tags do not get compiled into executable code, but provide
information to control how portions of your code get compiled.
The metadata tags define component attributes, data binding properties,
events, and other properties of the component. Flex interprets these statements during
compilation; they are never interpreted during run time.
Compiling Components
You set the ActionScript classpath by using the <source-path> tag in the flexconfig.xml
file.
MXML Components
Applying Styles from Components
In the definition of your custom component, you define styles by using one or both
of the
following mechanisms:
■ Tag properties
■ Class selectors
Note: You cannot define a type selector in an MXML component. If you define a
type selector,
a compiler error occurs.
Applying Styles from Reference file

Tag Properties
■ Class selectors
■ Type selectors
Advanced:
The best practice for defining components that return information back to the main
application is to design the component to dispatch an event that contains the return data.
In
that way, the main application can define an event listener to handle the event and take
the
appropriate action.
Binding
The Flex data binding mechanism provides a syntax for automatically copying the
value of a
property of one object to a property of another object at run time.
Formatters
For all formatter classes, except for the SwitchSymbolFormatter class, when an error
occurs,
the formatter returns an empty string and writes a string that describes the error condition
to
the formatter’s error property. The error property is inherited from the Formatter
superclass.
You can use the SwitchSymbolFormatter utility class when you create custom formatters.
You
use this class to replace placeholder characters in one string with numbers from a second
string.
For example, you specify the following information to the SwitchSymbolFormatter class:
Format string: “The Social Security number is: ###-##-####”
Input string: "123456789"
The SwitchSymbolFormatter class parses the format string and replaces each placeholder
character with a number from the input string in the order in which the numbers are
specified
in the input string. The default placeholder character is the number sign (#). You can
define a
different placeholder character by passing it to the constructor when you create a
SwitchSymbolFormatter object.
Validator.doValidation() method that takes a single argument, value, of type Object,
and returns an Array of ValidationResult objects.
Custom Effects
Flex implements effects by using an architecture in which each effect is represented
by two
classes: a factory class and an instance class. Therefore, to implement a custom effect,
you
create two classes: the factory class and the instance class.
You create a factory class by creating a subclass of the mx.effects.Effect class, or by
creating a
subclass of one of the subclasses of the mx.effects.Effect class. You create an instance
class by
creating a subclass of the mx.effects.EffectInstance class, or a subclass of one of the
subclasses
of the mx.effects.EffectInstance class.
Events in Action Script
The core class of the Flex architecture, mx.core.UIComponent
, defines core events,
such as
updateComplete
, resize
, move
, creationComplete
, and others that are fundamental to all
components.
Dispatching custom events
Your ActionScript component can define custom events and use the predefined events.
You
use custom events to support data binding, to respond to user interactions, or to trigger
actions by your component. For an example that uses events to support data binding, see
“Using data binding with custom properties” on page 132
.
For each custom event dispatched by your component, you must do the following:
1. Create an Event object describing the event.
2. (Optional) use the [Event] metadata tag to make the event public so that other
components can listen for it.
3. Dispatch the event by using the dispatchEvent() method.
Creating Custom Component using Action Script
This topic describes how to create advanced visual components in ActionScript. In ad
-
vanced
components, you typically perform the following actions:
■ Modify the visual appearance or visual characteristics of an existing component.
■ Create a composite component that encapsulates two or more components within it.
■ Create a component by creating a subclass of the UIComponent class.
Note: Flex uses an invalidation mechanism to synchronize modifications to components.
Flex
implements the invalidation mechanism as a set of methods that you call to signal that
something about the component has changed and requires Flex to call the component’s
commitProperties(), measure(), layoutChrome(), or updateDisplayList() methods.
Invalidation method Description
invalidateProperties() Marks a component so that its commitProperties() method gets
called during the next screen update.
invalidateSize() Marks a component so that its measure() method gets called
during the next screen update.
invalidateDisplayList() Marks a component so that its layoutChrome() and
updateDisplayList() methods get called during the next screen update
Tip: ActionScript does not support overloaded constructor methods.
Do not create child display objects in the constructor; you should use it only for setting
initial
properties of the component. If your component creates child components, create them in
the
createChildren() method.
You do not call the createChildren() method directly; Flex calls it when the call to the
addChild() method occurs to add the component to its parent. Notice that the
createChildren() method has no invalidation method, which means that you do not have
to call it a second time after the component is added to its parent.
Автор
ricozhot.
Документ
Категория
Без категории
Просмотров
202
Размер файла
116 Кб
Теги
flex, questions
1/--страниц
Пожаловаться на содержимое документа