设计松耦合的Flex组件 Design of loosely coupled components of the Flex
10月14th, 2006 — Dreamer 10月14 th, 2006 - Dreamer又看到一篇不错的Flex初级教程,翻译了过来。 Also see a good Flex primary guide, translated from. 翻译已经经过作者Marco Casario的同意,原文版权归原作者所有,译文版权归Dreamer所有。 After the author has been translated Marco Casario the consent of the original text belongs to original author, Dreamer: belongs to all. 此文未经同意,谢绝转载。 This article without consent, refused to reprint.
英文原文:http://mxdj.sys-con.com/read/276919_1.htm English text: http://mxdj.sys-con.com/read/276919_1.htm
作者: Marco Casario Author: Marco Casario
译者:Dreamer Translator: Dreamer
Flex应用程序可能有复杂的结构但它们通常都是由多个MXML,Actionscript 以及CSS文件组成。 Flex application may have a complex structure but they are usually by a number of MXML, Actionscript and CSS document composition.
在单个文件里编写整个程序不是一个最佳实践。 In a single document prepared by the whole process is not a best practice. 那样会使代码难以维护和重用,而且程序没有被架构成逻辑上的各个部分。 As will the code difficult to maintain and reuse, and procedures have not been a logical structure of the various parts.
Flex允许开发者将一个工程分成外部的模块,创建分离的MXML文件并且单独维护它们。 Flex allows developers to a project will be divided into external modules, the separation of MXML to create a separate document and preserve them. 将Flex程序分离成各个逻辑模块有很多好处。 Flex program will be separated into different logic modules have many advantages. 它允许开发小组独立地开发和调试单个模块,模块中的错误和功能可以被独立出来。 It allows the development of an independent group to develop and debug a single module, the mistakes in the module and function can be independent. 这使得代码变得容易维护,也提高了代码在多个应用程序间的重用性。 This makes it easy to maintain code, the code also increased in a number of applications between the reusability.
每个MXML文件是一个MXML组件,但是只有主MXML程序可以加载外部组件。 Each MXML document is a MXML components, but only the main MXML procedures can load external components. 事实上一个应用程序中只能有一个Application 标签,其它所有都是MXML组件。 In fact an application in the Application there can be only one label, all other components are MXML.
为了设计一个MXML组件,需要创建一个MXML文件。 In order to design a MXML components, the need to create a MXML document. 这个文件的根标签不是Application而是一个组件标签(比如VBox,Panel,Canvas,Button,DataGrid等等),而且根标签中需要声明命名空间http://www. adobe .com/2006/mxml 。 This document is not the root label Application but a component labels (such as VBox, Panel, Canvas, Button, DataGrid, etc.), and roots label needs statement naming space http://www. Adobe .com/2006/mxml.
下面的代码展示了一个简单的叫做custDataGrid.mxml 的MXML组件,它由一个用来存储数据的DataGrid组成。 Below the display of a simple code called custDataGrid.mxml the MXML components, used to store data from one of the DataGrid component.
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml"> <mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:DataGrid id="myDG" > <mx:DataGrid id="myDG">
<mx:columns>
<mx:DataGridColumn headerText="Posts" dataField="title" /> <mx:DataGridColumn headerText="Posts" dataField="title" />
<mx:DataGridColumn headerText="Date" dataField="pubDate" width="100" /> <mx:DataGridColumn headerText="Date" dataField="pubDate" width="100" />
</mx:columns> </ mx: columns>
</mx:DataGrid> </ mx: DataGrid>
</mx:VBox> </ mx: VBox>
根标签是一个简单的VBox组件并且其中声明了xmlns:mx="http://www.adobe.com/2006/mxml"。 Gen-label is a simple statement of VBox components and the xmlns: mx = "http://www.adobe.com/2006/mxml". 一旦创建了外部模块,主程序就可以像下面一样调用这个MXML组件: Once you create an external module, the main program can call this the same as below MXML components:
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:cust="comp.*" > <mx: Application xmlns: mx = "http://www.adobe.com/2006/mxml" layout = "absolute" xmlns: cust = "comp .* & # 34;>
<mx:Panel title="Comtaste's Blog Reader"> <mx:Panel title="Comtaste's Blog Reader">
<cust: custDataGrid width="80%" /> <cust: custDataGrid width="80%" />
</mx:Panel> </ mx: Panel>
</mx:Application> </ mx: Application>
主程序添加了一个新的XML命名空间并使用一个包名来表示在一个文件夹中定义的所有组件: Main program to add a new XML namespace and use that name to a package in a folder in the definition of all components:
“cust”命名空间指向”comp”文件夹中的MXML组件,实际上如果是最佳实践所有的组件都应当被保存在一个子目录下。 "Cust" naming space at the "comp" folder in the MXML components, is the best practice if in fact all the components should be stored in a subdirectory.
使用组件和使用其它MXML标签一样,唯一不同的是不再使用”mx”前缀而是使用自定义前缀: The use of components and the use of other MXML tag, the only difference is no longer in use "mx" prefix but use a custom prefix:
注意MXML标签的名字对应着这个组件的文件名。 Note MXML tab corresponding to the names of the components of the file name.
紧耦合组件与松耦合组件 Tightly coupled components and loosely coupled components
为了使组件在程序中可以配置和重用,你可能会想要创建可以接受属性,创建方法以及分派事件的MXML组件。 In order to make components in the proceedings can be configured and reuse, you may want to create acceptable properties, and create a method of distribution of the incident MXML components. 为了做到这样,组件必须不依赖于特定的程序(紧耦合),包括它们的变量名或标签实例的名字。 To do so, the components must not rely on specific procedures (tight coupling), including their variable name or the name of examples of labels. 紧耦合情况下如果程序或者组件的代码改变了,相应的代码就不能再工作,我们必须修改紧耦合的组件来相应这些变化。 Tight coupling procedures if circumstances or components of the code has changed, the corresponding code can no longer work, we need to revise the tight coupling of the components corresponding to these changes.
一种更清晰也更好的方式是开发松耦合的组件,它可以分派传播返回数据给程序的事件并且包含一些属性使得可以从程序传送信息给它。 A clearer and better way is the development of loosely coupled components, it can be assigned to return to the dissemination of data to process the events and include a number of attributes can be made from the process send messages to it.
这种方式可以让你像创建“黑盒子”一样创建MXML组件,并且有以下好处: This allows you to create as the "black box" like a MXML components, and has the following advantages:
•它们容易重用和维护•除了内部的组件它们不了解其它的东西•它们不依赖于一个变量名和标签实例的名字 • they are easy to reuse and maintenance • In addition to the internal components of the other things they do not understand • they do not rely on a variable name and the name of examples of labels
如我们所说的那样,为了创建一个松耦合的组件我们需要属性来存储信息,需要一个事件模型来分派包含有返回数据的事件。 As we have said, in order to create a loosely coupled components we need to attribute to store information, the need to assign an event model contains data back to the events.
属性经常在ActionScript中定义(尽管你可以在MXML中定义它们)并且放在一个<mx:Script>块中: Properties often defined in the ActionScript (although you can define them in MXML) and in a <mx: Script> block:
<![CDATA[ <! [CDATA [
import mx.collections.ArrayCollection; import mx.collections.ArrayCollection;
[Bindable]
public var lista:ArrayCollection; public var lista: ArrayCollection;
]]> ] ">
</mx:Script> </ mx: Script>
定义MXML组件的方法也是一样: MXML components definition of the method is the same:
<![CDATA[ <! [CDATA [
import mx.collections.ArrayCollection; import mx.collections.ArrayCollection;
[Bindable]
public var lista:ArrayCollection; public var lista: ArrayCollection;
public function justWrite():String public function justWrite (): String
{ (
return "This is a method of the component"; return "This is a method of the component";
} )
]]> ] ">
</mx:Script> </ mx: Script>
在下面的例子中,组件定义了一个作为DataGrid的dataProvider的属性和一个返回字符串的方法。 In the example below, the definition of a component of the dataProvider DataGrid as the return of properties and a string method. 下面是custDataGrid.mxml 文件的全部代码: Below is the full document custDataGrid.mxml code:
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml"> <mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[ <! [CDATA [
import mx.collections.ArrayCollection; import mx.collections.ArrayCollection;
[Bindable]
public var lista:ArrayCollection; public var lista: ArrayCollection;
public function justWrite():String public function justWrite (): String
{ (
return "This is a method of the component"; return "This is a method of the component";
} )
]]> ] ">
</mx:Script> </ mx: Script>
<mx:DataGrid id="myDG" dataProvider="{lista}" > <mx:DataGrid id="myDG" dataProvider="{lista}">
</mx:DataGrid> </ mx: DataGrid>
</mx:VBox> </ mx: VBox>
Flex 2文档中的声明 :在<mx:Script>标签中声明的公有变量或set函数会是这个组件的一个属性。 Flex 2 document in a statement: <mx: Script> tab in the public statement or set variable function of this component will be an attribute. <mx:Script>标签中的公有函数会是组件的一个方法。 <mx:Script> tab of the public function is a component of the way.
我们可以在主程序文件中访问组件的方法或者传值给组件的属性: We can access documents in the main program components-the method or components to the value of the properties:
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:cust="*"> <mx: Application xmlns: mx = "http://www.adobe.com/2006/mxml" layout = "absolute" xmlns: cust = "*" ;>
<mx:Script>
<![CDATA[ <! [CDATA [
import mx.collections.ArrayCollection; import mx.collections.ArrayCollection;
[Bindable]
public var myData:ArrayCollection = new ArrayCollection ( public var myData: ArrayCollection = new ArrayCollection (
[{A:2000},{A:3000},{A:4000},{A:4000},{A:3000},{A:2000},{A:6000}]); [(A: 2000), (A: 3000), (A: 4000), (A: 4000), (A: 3000), (A: 2000), (A: 6000)]);
]]> ] ">
</mx:Script> </ mx: Script>
<cust:custDataGrid id="custDG" x="258" y="89" lista="{myData}"/> <cust:custDataGrid id="custDG" x="258" y="89" lista="{myData}"/>
<mx:Label text="{custDG.justWrite()}" x="300" y="44"/> <mx:Label text="{custDG.justWrite()}" x="300" y="44"/>
</mx:Application> </ mx: Application>
在主程序中我们创建了一个叫做”myData”的ArrayCollection变量,我们可以通过下面的方法在MXML组件标签声明中将它传递给组件: In the main program, we created a called "myData" the ArrayCollection variables, we can through the following methods in MXML components labelling statement, it passed to the components:
我们用来展示自定义组件中定义的属性的Flex数据绑定机制可以利用数据绑定特性。 We used to display customized components in the definition of the attributes of Flex data binding mechanism can use the data binding characteristics. ”lista”变量是custDataGrid组定义组件的一个公有变量,所以我们将它写在custDataGrid标签声明中。 "Lista" custDataGrid group is variable component of the definition of a public variable, so we have to write it in custDataGrid label statement.
类似地,也可以创建一个数据绑定调用自定义组件中的一个方法: Similarly, can also create a data binding call custom components in a way:
Label控件的text属性将接收自定义组件custDataGrid的公有方法返回的文本: Label controls the text attributes will receive customized components custDataGrid way back to the public the text:
{ (
return "This is a method of the component"; return "This is a method of the component";
} )
设计一个松耦合组件的最后一步是处理包含返回数据的事件的分派。 The design of a loosely coupled components of the final step is to include data back to the events assigned. 每个自定义MXML组件都可分派事件,事件可以通过三个简单的步骤自定义: Each custom MXML components can be distributed, through three events can be custom simple steps:
•使用[Event]元数据标签•创建一个事件对象•分派事件并创建一个函数来处理该事件 • the use of [Event] meta-data tags to create an event object • • assigned events and create a function to deal with the incident
[Event]元数据标签定义了组件可以分派的事件。 [Event] metadata labels can be assigned definition of the components of the incident. 可以在一个ActionScript类中包定义之后类定义之前声明[Event]元数据标签: ActionScript in a defined category after category definition package before the statement [Event] metadata labels:
{ (
[Event(name=" changeBlog", type=" flash.events.Event ")] [Event (name = "changeBlog", type = "flash.events.Event")]
public class custComp public class custComp
{ (
} )
} )
或者在MXML文件中的<mx:Metadata>标签中: MXML document or in the <mx: Metadata> tab:
[Event(name="changeBlog", type=" flash.events.Event ")] [Event (name = "changeBlog", type = "flash.events.Event")]
</mx:Metadata> </ mx: Metadata>
一旦[Event]元数据标签创建,组件就可以使用dispatchEvent()方法来分派该事件。 Once [Event] meta-data tags to create, components can use dispatchEvent () method to distribute the incident. dispatchEvent()方法将事件对象作为参数,如下面的代码中所示: dispatchEvent () method event object as a parameter, as shown in the following code:
我们来修改一下custDataGrid.mxml文件,使其可以在用户点击DataGrid中一项的时候分派一个事件。 We custDataGrid.mxml to amend the document so that it can be a user clicks on a DataGrid in the time assigned an event. 主程序将处理自定义组件触发的事件并在一个TextArea控件中添加一些文字。 Since the main program will address the definition of components to trigger the events in a TextArea control and add some text.
使用Flex Builder 2打开custDataGrid.mxml 并添加[Event]元数据标签: The use of Flex Builder 2 custDataGrid.mxml open and add [Event] metadata labels:
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml"> <mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Metadata>
[Event(name="changeBlog", type="flash.events.Event")] [Event (name = "changeBlog", type = "flash.events.Event")]
</mx:Metadata> </ mx: Metadata>
<mx:Script>
<![CDATA[ <! [CDATA [
import mx.collections.ArrayCollection; import mx.collections.ArrayCollection;
[Bindable]
public var lista:ArrayCollection; public var lista: ArrayCollection;
public function justWrite():String public function justWrite (): String
{ (
return "This is a method of the component"; return "This is a method of the component";
} )
private function changeHandler():void private function changeHandler (): void
{ (
dispatchEvent(new Event("changeBlog")); dispatchEvent (new Event ( "changeBlog"));
} )
]]> ] ">
</mx:Script> </ mx: Script>
<mx:DataGrid id="myDG" dataProvider="{lista}" change="changeHandler()" > <mx:DataGrid id="myDG" dataProvider="{lista}" change="changeHandler()">
</mx:DataGrid> </ mx: DataGrid>
</mx:VBox> </ mx: VBox>
[Event]元数据标签定义了一个普通Event类型的"changeBlog"事件并且将这个事件设为公有的,这样MXML编译器就会发现它。 [Event] metadata labels Event definition of a common type of "changeBlog" this incident and will set public events, such MXML compiler will find it.
[Event(name="changeBlog", type="flash.events.Event")] [Event (name = "changeBlog", type = "flash.events.Event")]
</mx:Metadata> </ mx: Metadata>
当DataGrid的change事件被触发时这个事件就会被分派: When the change DataGrid incident was triggered when this incident will be assigned:
正如你看到的那样,"changeHandler"函数简单地执行了dispatchEvent()方法: As you see it, "changeHandler" to implement a simple function dispatchEvent ():
{ (
dispatchEvent(new Event("changeBlog")); dispatchEvent (new Event ( "changeBlog"));
} )
主程序通过使用<mx:Script>块中定义的事件处理函数来处理自定义MXML组件所触发的事件: Main program through the use of <mx: Script> block in the definition of the incident function to deal with custom MXML components triggered by the events:
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:cust="*"> <mx: Application xmlns: mx = "http://www.adobe.com/2006/mxml" layout = "absolute" xmlns: cust = "*" ;>
<mx:Script>
<![CDATA[ <! [CDATA [
import mx.collections.ArrayCollection; import mx.collections.ArrayCollection;
[Bindable]
public var myData:ArrayCollection = new ArrayCollection ( public var myData: ArrayCollection = new ArrayCollection (
[{A:2000},{A:3000},{A:4000},{A:4000},{A:3000},{A:2000},{A:6000}]); [(A: 2000), (A: 3000), (A: 4000), (A: 4000), (A: 3000), (A: 2000), (A: 6000)]);
private function changeBlogHandler (event:Event):void private function changeBlogHandler (event: Event): void
{ (
myLabel2.text = "Event fired by Datagrid:" event.type "\n" ; myLabel2.text = "Event fired by Datagrid:" event.type "\ n";
} )
]]> ] ">
</mx:Script> </ mx: Script>
<cust:custDataGrid id="custDG" x="258" y="89" lista="{myData}" changeBlog="changeBlogHandler(event)"/> <cust: custDataGrid id = "custDG" x = "258" y = "89" lista = "(myData)" changeBlog = & # 34; changeBlogHandler (event) "/>
<mx:Label text="{custDG.justWrite()}" id="myLabel" x="283" y="63"/> <mx: Label text = "(custDG.justWrite ())" id = "myLabel" x = "283" y = "63" ; />
<mx:TextArea id="myLabel2" x="205" y="239" height="102" width="273"/> <mx: TextArea id = "myLabel2" x = "205" y = "239" height = "102" width = " 273 "/>
</mx:Application> </ mx: Application>
custDataGrid组件触发"changeBlog"事件并将它与一个事件处理函数相关联: custDataGrid components trigger "changeBlog" incident and an incident with the function associated with:
changeBlogHandler函数将事件对象作为一个参数并在TextAream控件中打印了一个简单的文本: changeBlogHandler event objects will function as a parameter in TextAream control and to print a simple text:
{ (
myLabel2.text = "Event fired by Datagrid:" event.type "\n" ; myLabel2.text = "Event fired by Datagrid:" event.type "\ n";
} )
注意使用事件对象的event.type 会返回事件触发者的类型(这个例子中会返回changeblog )。 The use of the event.type event object will return to trigger the type of incident (in this example will return to changeblog).
注意 :Flex Builder 2会自动找到在组件中自定义事件的引用并使用显示代码提示显示它: Note: Flex Builder 2 will automatically find in custom components in the incident and cited the use of code that it tips:
尽管我们可以看到为松耦合组件创建一个自定义事件是多么简单,但是如果我们想要发送数据给这个自定义事件,这种方式也会有一些限制。 Although we can see that the loosely coupled components to create a custom case is so simple, but if we want to send data to the custom, this way there will be some restrictions. 实际上flash.events.Event类不允许开发者向其添加属性。 In fact flash.events.Event category does not allow developers to add attributes.
实际上我们分派事件只是为了通知在自定义MXML组件中有一些事情发生了。 In fact, we distributed only to let the incident in custom MXML components in a number of things happened. 但是如果我们需要发送复杂的数据给一个自定义事件的时候要怎么办呢? However, if we need to send complex data to a custom when the incident to how to do »
不用担心。 Do not worry. 我们可以通过在ActionScript中创建自定义事件类来实现! We can in ActionScript create custom events in the category to achieve! 我将会通过一个例子向你展示如何开发自定义事件类。 I will be through an example to show you how to develop custom events category.
在ActionScript中创建自定义事件类来发送复杂数据 In ActionScript create custom events in the category to send complex data
使用Flex可以创建一个使用自定义类型的事件对象的自定义事件。 The use of the use of Flex can create a custom type of event objects custom events. 只需要创建一个扩展自Event类的子类然后向其中添加属性。 Only need to create a kind of expansion since the Event of which add to the class and attributes. 不要忘了扩展自既有Flex类的自定义组件会继承基类的所有事件。 Do not forget to expand the existing Flex components such as custom base class will inherit all the events.
要创建一个自定义类我们需要创建一个扩展自flash.events.Event的ActionScript类,这个类将作为所有事件对象的基类。 To create a custom category we need to create a flash.events.Event expansion since the ActionScript class that will serve as the object of all events category. 接下来,为了调用父类的构造方法并将事件类型传给它,我们要调用super()方法。 Next, in order to call the father of categories by type of construction method and pass it, we have to call super () method. 我们还需要覆写"clone()" 方法,通过设定type属性和其它一些属性来返回事件对象的一个拷贝。 We also need to override the "clone ()" method, set type and other attributes some attribute to return to a copy of the event object.
为了从自定义组件中分派一个新的事件,我们创建了这个自定义类的一个实例并传送属性值给它。 In order to distribute customized components in a new incident, we created a definition of this category since an example and send property values to it.
现在我会用一个例子来说明这种方式。 I will now use an example to illustrate this approach. 我们创建了一个简单的Blog阅读器,它允许用户使用下拉列表框从Blog列表中选择一个。 We created a simple Blog readers, it allows users to use the drop-down list box from the list, select a Blog. 这个程序由2个MXML组件组成,这两个组件是一个用来显示日志内容的DataGrid以及一个含有Blog列表下拉列表框。 This procedure by the two components comprising MXML, these two components is a log to show that the content of the Blog DataGrid and a list containing the drop-down list box.
我们将从一个自定义事件类(它被保存为"evtClass.as",并放在了”com”文件夹里)开始,它接受一个简单字符串属性: We will be a custom event category (it was saved as "evtClass.as", and on the "com" folder), its acceptance of a simple string attributes:
{ (
import flash.events.Event; import flash.events.Event;
public class evtClass extends Event public class evtClass extends Event
{ (
public var evProp:String; public var evProp: String;
public function evtClass(evParam:String,type:String) public function evtClass (evParam: String, type: String)
{ (
super(type); super (type);
this.evProp = evParam; this.evProp = evParam;
} )
override public function clone():Event override public function clone (): Event
{ (
return new evtClass(evProp,type); return new evtClass (evProp, type);
} )
} )
} )
象我们之前说的那样,这个类扩展自flash.events.Event类,调用了super()方法并且覆写了clone()方法。 As we said before, as this category flash.events.Event expansion of the category, called the super () method and override the clone () method.
现在,在Flex Builder 2中创建一个组件(File > New > MXML Component)并保存为custBlogList.mxml。 Now, in Flex Builder 2 in the creation of a component (File> New> MXML Component) and save it as a custBlogList.mxml. 这个组件包含有一个下拉列表框(ComboBox)并且它的dataProvider是一个ArrayCollection对象。 The components include a drop-down list box (ComboBox) and its dataProvider is a ArrayCollection object.
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml" > <mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Metadata>
[Event(name="changeBlog", type="com.evtClass")] [Event (name = "changeBlog", type = "com.evtClass")]
</mx:Metadata> </ mx: Metadata>
<mx:Script>
<![CDATA[ <! [CDATA [
import com.evtClass; import com.evtClass;
private function init():void private function init (): void
{ (
myArray.addItemAt({label:"Alistair McLeod", data:"http://weblogs.macromedia.com/amcleod/index.xml"}, 0); myArray.addItemAt ((label: "Alistair McLeod", data: "http://weblogs.macromedia.com/amcleod/index.xml"), 0);
} )
private function changeHandler():void private function changeHandler (): void
{ (
var eventObj:evtClass = new evtClass(myCombo.value as String,"changeBlog"); var eventObj: evtClass = new evtClass (myCombo.value as String, "changeBlog");
dispatchEvent(eventObj); dispatchEvent (eventObj);
} )
]]> ] ">
</mx:Script> </ mx: Script>
<mx:ComboBox id="myCombo" change="changeHandler()" creationComplete="init();myCombo.selectedIndex=0" > <mx:ComboBox id="myCombo" change="changeHandler()" creationComplete="init();myCombo.selectedIndex=0">
<mx:ArrayCollection id="myArray"> <mx:ArrayCollection id="myArray">
<mx:Object label="Mike Chambers" data="http://weblogs.macromedia.com/mesh/index.xml"/> <mx:Object label="Mike Chambers" data="http://weblogs.macromedia.com/mesh/index.xml"/>
<mx:Object label="Matt Chotin" data="http://weblogs.macromedia.com/mchotin/index.xml"/> <mx:Object label="Matt Chotin" data="http://weblogs.macromedia.com/mchotin/index.xml"/>
</mx:ArrayCollection> </ mx: ArrayCollection>
</mx:ComboBox> </ mx: ComboBox>
</mx:VBox> </ mx: VBox>
我们使用了[Event]元数据标签定义了这个MXML组件可以分派的事件。 We use the [Event] metadata definition of the label this MXML components can be assigned the case. 赋给type属性的值就是我们的自定义事件类: Assign a value type attribute is our custom event categories:
[Event(name="changeBlog", type="com.evtClass")] [Event (name = "changeBlog", type = "com.evtClass")]
</mx:Metadata> </ mx: Metadata>
一旦用户在下拉列表框中选择了一个Blog,change事件就会被触发并且changeHandler()会被调用: Once the user in the drop-down list box, choose a Blog, change events will be triggered and changeHandler () will be called:
这个事件处理器只有一个作用,就是创建一个自定义事件类的实例并将用户所选择的值传送给这个实例(将myCombo中的值作为一个字符串): The incident only one processor, is to create a custom category of incidents and examples of the value chosen by the user to send this case (to be myCombo in value as a string):
{ (
var eventObj:evtClass = new evtClass(myCombo.value as String,"changeBlog"); var eventObj: evtClass = new evtClass (myCombo.value as String, "changeBlog");
dispatchEvent(eventObj); dispatchEvent (eventObj);
} )
第二个MXML组件包含了DataGrid控件并且从主程序中接收dataProvider。 The second component includes the MXML DataGrid control from the main program and receive dataProvider. 现在你需要将这个文件保存为custBlogData.mxml: Now you need to save a file in this custBlogData.mxml:
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml"> <mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[ <! [CDATA [
import mx.collections.ArrayCollection; import mx.collections.ArrayCollection;
import flash.net.*; import flash.net .*;
[Bindable]
public var lista:ArrayCollection; public var lista: ArrayCollection;
]]> ] ">
</mx:Script> </ mx: Script>
<mx:DataGrid id="myDG" horizontalCenter="14" verticalCenter="18.5" dataProvider="{lista}" width="100%" <mx: DataGrid id = "myDG" horizontalCenter = "14" verticalCenter = "18.5" dataProvider = "(lista)" width = "100%"
change="navigateToURL(new URLRequest(myDG.selectedItem.link),'_blank');" > change = "navigateToURL (new URLRequest (myDG.selectedItem.link), '_blank');">
<mx:columns>
<mx:DataGridColumn headerText="Posts" dataField="title" /> <mx:DataGridColumn headerText="Posts" dataField="title" />
<mx:DataGridColumn headerText="Date" dataField="pubDate" width="100" /> <mx:DataGridColumn headerText="Date" dataField="pubDate" width="100" />
</mx:columns> </ mx: columns>
</mx:DataGrid> </ mx: DataGrid>
</mx:VBox> </ mx: VBox>
这个DataGrid定义了两列。 This DataGrid definition of the two. 第一列从用户选择的RSS feed(在custBlogList中选择的)中获取数据。 The first column from the user's choice of RSS feed (in custBlogList in the choice of) access to data. 第二列从类型为ArrayCollection 的变量"lista" 获取数据。 The second column from the types of variables ArrayCollection "lista" access to data.
接下来,就是主程序文件了(BlogReader.mxml),它会调用上面的两个组件,调用一个HTTPService来获取rss数据并且定义了一个事件处理函数: Next, the document is the main program (BlogReader.mxml), it will call the above two components, one HTTPService call to obtain rss and definition of a data processing function of the incident:
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:cust="*" <mx: Application xmlns: mx = "http://www.adobe.com/2006/mxml" layout = "absolute" xmlns: cust = "*" ;
creationComplete="hs.send()" > creationComplete = "hs.send ()">
<mx:HTTPService <mx: HTTPService
id="hs" id = "hs"
url="{selectedMenu}" url = "(selectedMenu)"
useProxy="false"/> useProxy = "false" />
<mx:Script>
<![CDATA[ <! [CDATA [
import com.evtClass; import com.evtClass;
[Bindable]
private var selectedMenu:String= "http://weblogs.macromedia.com/amcleod/index.xml"; private var selectedMenu: String = "http://weblogs.macromedia.com/amcleod/index.xml";
private function eventFired(event:evtClass):void private function eventFired (event: evtClass): void
{ (
selectedMenu = event.evProp; selectedMenu = event.evProp;
if (selectedMenu == "null") if (selectedMenu == "null")
{ (
mx.controls.Alert.show("Please Choose a valid Blog"); mx.controls.Alert.show ( "Please Choose a valid Blog");
return;
}; );
hs.send(); hs.send ();
} )
]]> ] ">
</mx:Script> </ mx: Script>
<mx:Panel width="70%" height="70%" layout="absolute" title="Comtaste's Blog Reader" horizontalCenter="0" <mx: Panel width = "70%" height = "70%" layout = "absolute" title = "Comtaste's Blog Reader "horizontalCenter =" 0 "
verticalCenter="-14.5"> verticalCenter = "-14.5">
<mx:Label text="{hs.lastResult.rss.channel.title}'s Blog" id="myLbl" x="48.5" y="43" fontWeight="bold"/> <mx: Label text = "(hs.lastResult.rss.channel.title) 's Blog" id = "myLbl" x = "48.5" ; Y = "43" fontWeight = "bold" />
<cust:custBlogList x="161" y="10" changeBlog="eventFired(event)" /> <cust:custBlogList x="161" y="10" changeBlog="eventFired(event)" />
<mx:Label x="48.5" y="10" text="Select a Blog" height="25"/> <mx: Label x = "48.5" y = "10" text = "Select a Blog" height = "25" ; />
<cust:custBlogData width="80%" x="48.5" y="69" lista="{hs.lastResult.rss.channel.item}" /> <cust: custBlogData width = "80%" x = "48.5" y = "69" lista = "(hs.lastResult.rss. channel.item) "/>
<mx:ControlBar>
<mx:Label text="Developed by Marco Casario" /> <mx:Label text="Developed by Marco Casario" />
<mx:LinkButton label="http://casario.blogs.com" click="navigateToURL(new <mx: LinkButton label = "http://casario.blogs.com" click = "navigateToURL (new
URLRequest('http://casario.blogs.com'),'_blank');"/> URLRequest ( 'http://casario.blogs.com'),'_ blank');"/>
</mx:ControlBar> </ mx: ControlBar>
</mx:Panel> </ mx: Panel>
</mx:Application> </ mx: Application>
HTTPService标签对它的url属性进行了数据绑定。 HTTPService label the url attribute it to the data binding. 当custBlogList中的changeBlog事件触发时{selectedMenu}的值就会被确定: When custBlogList in changeBlog incident triggered when (selectedMenu) value will be determined:
id="hs" id = "hs"
url="{selectedMenu}" url = "(selectedMenu)"
useProxy="false"/> useProxy = "false" />
<cust:custBlogList x="161" y="10" changeBlog="eventFired(event)" /> <cust:custBlogList x="161" y="10" changeBlog="eventFired(event)" />
eventFired()是一个事件处理器,它使用事件对象来获取在actionscript(evtClass.as)类中定义的evProp,它包含myCombo的值: eventFired () is an event processor, which uses the event object to obtain the actionscript (evtClass.as) categories defined in the evProp, it contains myCombo values:
{ (
selectedMenu = event.evProp; selectedMenu = event.evProp;
if (selectedMenu == "null") if (selectedMenu == "null")
{ (
mx.controls.Alert.show("Please Choose a valid Blog"); mx.controls.Alert.show ( "Please Choose a valid Blog");
return;
}; );
hs.send(); hs.send ();
} )
松耦合的组件是Flex 2程序中一个强大的工具,因为这使得开发者可以提高代码的重用性和可维护性。 Loosely coupled components of Flex 2 is the process of a powerful tool because it makes developers can increase code reuse and maintainability. 使用这种方式可以定义在多个程序中都能使用的响应不同用户交互的逻辑模块。 The use of such methods can be defined in a number of procedures can be used in response to different user interaction logic modules.
模块也可以被自定义成包含有能够接收其它模块传值的属性以及可以返回信息的事件。 Modules can also be customized to include other modules are able to receive the property-value information and can return to the incident.
本文链接: http://www.zhuoqun.net/html/y2006/276.html 转载请注明出处,谢谢。 This link: http://www.zhuoqun.net/html/y2006/276.html reprint please reference, thank you.


