flex 实用公式

 

实用公式 

    统领全书,我们已经有了各种运动和效果的公式。我已经提取出了最实用和最常用的公式、方程、以及代码的摘录,并将它们列在本章的最后。我认为将它们放到同一个地方应该对大家非常有帮助,因此我将这些我认为最需要的内容放到一起作为整体的一个参考资料。我将会在这一页夹上书签。 

 

 

第三章 
基础三角函数的计算: 
角的正弦值 = 对边 / 斜边 
角的余弦值 = 邻边 / 斜边 
角的正切值 = 对边 / 邻边 

 

弧度转换为角度以及角度转换为弧度: 
弧度 = 角度 * Math.PI / 180 
角度 = 弧度 * 180 / Math.PI 

 

向鼠标(或者任何一个点)旋转: 
// 用要旋转到的 x, y 坐标替换 mouseX, mouseY 
dx = mouseX - sprite.x; 
dy = mouseY - sprite.y; 
sprite.rotation = Math.atan2(dy, dx) * 180 / Math.PI; 

 

创建波形: 
// 将 x, y 或其它属性赋值给 Sprite 影片或影片剪辑, 
// 作为绘图坐标,等等。 
public function onEnterFrame(event:Event){ 
value = center + Math.sin(angle) * range; 
angle += speed; 

 

创建圆形: 
// 将 x, y 或其它属性赋值给 Sprite 影片或影片剪辑, 
// 作为绘图坐标,等等。 
public function onEnterFrame(event:Event){ 
xposition = centerX + Math.cos(angle) * radius; 
yposition = centerY + Math.sin(angle) * radius; 
angle += speed; 

 

创建椭圆: 
// 将 x, y 或其它属性赋值给 Sprite 影片或影片剪辑, 
// 作为绘图坐标,等等。 
public function onEnterFrame(event:Event){ 
xposition = centerX + Math.cos(angle) * radiusX; 
yposition = centerY + Math.sin(angle) * radiusY; 
angle += speed; 

 

获得两点间的距离: 
// x1, y1 和 x2, y2 是两个点 
// 也可以是 Sprite / MovieClip 坐标,鼠标坐标,等等。 
dx = x2 – x1; 
dy = y2 – y1; 
dist = Math.sqrt(dx*dx + dy*dy); 

 

第四章 

十六进制转换为十进制: 
trace(hexValue); 

 

十进制转换为十六进制: 
trace(decimalValue.toString(16)); 

 

颜色组合: 
color24 = red << 16 | green << 8 | blue; 
color32 = alpha << 24 | red << 16 | green << 8 | blue; 

 

颜色提取: 
red = color24 >> 16; 
green = color24 >> 8 & 0xFF; 
blue = color24 & 0xFF; 
alpha = color32 >> 24; 
red = color32 >> 16 & 0xFF; 
green = color32 >> 8 & 0xFF; 
blue = color232 & 0xFF; 

 

穿过某点绘制曲线: 
// xt, yt 是我们想要穿过的一点 
// x0, y0 以及 x2, y2 是曲线的两端 
x1 = xt * 2 – (x0 + x2) / 2; 
y1 = yt * 2 – (y0 + y2) / 2; 
moveTo(x0, y0); 
curveTo(x1, y1, x2, y2); 

 

第五章 
角速度转换为 x, y 速度: 
vx = speed * Math.cos(angle); 
vy = speed * Math.sin(angle); 

 

角加速度(作用于物体上的 force)转换为 x, y 加速度: 
ax = force * Math.cos(angle); 
ay = force * Math.sin(angle); 

 

将加速度加入速度: 
vx += ax; 
vy += ay; 

 

将速度加入坐标: 
movieclip._x += vx; 
sprite.y += vy; 

 

第六章 
移除出界对象: 
if(sprite.x - sprite.width / 2 > right || 
sprite.x + sprite.width / 2 < left || 
sprite.y – sprite.height / 2 > bottom || 
sprite.y + sprite.height / 2 < top) 

// 删除影片的代码 

 

重置出界对象: 
if(sprite.x - sprite.width / 2 > right || 
sprite.x + sprite.width / 2 < left || 
sprite.y – sprite.height / 2 > bottom || 
sprite.y + sprite.height / 2 < top) 

// 重置影片的位置和速度 

 

屏幕环绕出界对象: 
if(sprite.x - sprite.width / 2 > right) 

sprite.x = left - sprite.width / 2; 

else if(sprite.x + sprite.width / 2 < left) 

sprite.x = right + sprite.width / 2; 

if(sprite.y – sprite.height / 2 > bottom) 

sprite.y = top – sprite.height / 2; 

else if(sprite.y + sprite.height / 2 < top) 

sprite.y = bottom + sprite.height / 2; 

 

摩擦力应用(正确方法): 
speed = Math.sqrt(vx * vx + vy * vy); 
angle = Math.atan2(vy, vx); 
if(speed > friction) 

speed -= friction; 

else 

speed = 0; 

vx = Math.cos(angle) * speed; 
vy = Math.sin(angle) * speed; 

 

摩擦力应用(简便方法): 
vx *= friction; 
vy *= friction; 

 

第八章: 
简单缓动运动,长形: 
var dx:Number = targetX - sprite.x; 
var dy:Number = targetY - sprite.y; 
vx = dx * easing; 
vy = dy * easing; 
sprite.x += vx; 
sprite.y += vy; 

 

简单缓动运动,中形: 
vx = (targetX - sprite.x) * easing; 
vy = (targetY - sprite.y) * easing; 
sprite.x += vx; 
sprite.y += vy; 

 

简单缓动运动,短形: 
sprite.x += (targetX - sprite.x) * easing; 
sprite.y += (targetY - sprite.y) * easing; 

 

简单弹性运动,长形: 
var ax:Number = (targetX - sprite.x) * spring; 
var ay:Number = (targetY - sprite.y) * spring; 
vx += ax; 
vy += ay; 
vx *= friction; 
vy *= friction; 
sprite.x += vx; 
sprite.y += vy; 

 

简单弹性运动,中形: 
vx += (targetX - sprite.x) * spring; 
vy += (targetY - sprite.y) * spring; 
vx *= friction; 
vy *= friction; 
sprite.x += vx; 
sprite.y += vy; 

 

简单弹性运动,短形: 
vx += (targetX - sprite.x) * spring; 
vy += (targetY - sprite.y) * spring; 
sprite.x += (vx *= friction); 
sprite.y += (vy *= friction); 

 

偏移弹性运动: 
var dx:Number = sprite.x - fixedX; 
var dy:Number = sprite.y - fixedY; 
var angle:Number = Math.atan2(dy, dx); 
var targetX:Number = fixedX + Math.cos(angle) * springLength; 
var targetY:Number = fixedX + Math.sin(angle) * springLength; 
// 如前例弹性运动到 targetX, targetY 

 

第九章 
距离碰撞检测: 
// 从影片 spriteA 和 spriteB 开始 
// 如果使用一个空白影片,或影片没有半径(radius)属性 
// 可以用宽度或高度除以 2。 
var dx:Number = spriteB.x - spriteA.x; 
var dy:Number = spriteB.y - spriteA.y; 
var dist:Number = Math.sqrt(dx * dx + dy * dy); 
if(dist < spriteA.radius + spriteB.radius) 

// 处理碰撞 

 

多物体碰撞检测: 
var numObjects:uint = 10; 
for(var i:uint = 0; i < numObjects - 1; i++) 

// 使用变量 i 提取引用 
var objectA = objects[i]; 
for(var j:uint = i+1; j 

  // // 使用变量 j 提取引用 
  var objectB = objects[j]; 
  // perform collision detection 
  // between objectA and objectB 

 

第十章 
坐标旋转: 
x1 = Math.cos(angle) * x - Math.sin(angle) * y; 
y1 = Math.cos(angle) * y + Math.sin(angle) * x; 

 

反坐标旋转: 
x1 = Math.cos(angle) * x + Math.sin(angle) * ;y 
y1 = Math.cos(angle) * y - Math.sin(angle) * x; 

 

第十一章 
动量守恒的数学表达式: 
                (m0 – m1) * v0 + 2 * m1 * v1 
v0Final = ---------------------------------------------- 
                          m0 + m1 

                (m1 – m0) * v1 + 2 * m0 * v0 
v1Final = --------------------------------------------- 
                          m0 + m1 


动量守恒的 ActionScript 表达式,短形: 
var vxTotal:Number = vx0 - vx1; 
vx0 = ((ball0.mass - ball1.mass) * vx0 + 
2 * ball1.mass * vx1) / 
(ball0.mass + ball1.mass); 
vx1 = vxTotal + vx0; 

 

第十二章 
引力的一般公式: 
force = G * m1 * m2 / distance2 

 

ActionScript 实现万有引力: 
function gravitate(partA:Ball, partB:Ball):void 

var dx:Number = partB.x - partA.x; 
var dy:Number = partB.y - partA.y; 
var distSQ:Number = dx * dx + dy * dy; 
var dist:Number = Math.sqrt(distSQ); 
var force:Number = partA.mass * partB.mass / distSQ; 
var ax:Number = force * dx / dist; 
var ay:Number = force * dy / dist; 
partA.vx += ax / partA.mass; 
partA.vy += ay / partA.mass; 
partB.vx -= ax / partB.mass; 
partB.vy -= ay / partB.mass; 

 

第十四章 
余弦定理 
a2 = b2 + c2 - 2 * b * c * cos A 
b2 = a2 + c2 - 2 * a * c * cos B 
c2 = a2 + b2 - 2 * a * b * cos C 

 

ActionScript 的余弦定理: 
A = Math.acos((b * b + c * c - a * a) / (2 * b * c)); 
B = Math.acos((a * a + c * c - b * b) / (2 * a * c)); 
C = Math.acos((a * a + b * b - c * c) / (2 * a * b)); 

 

第十五章 
基本透视法: 
scale = fl / (fl + zpos); 
sprite.scaleX = sprite.scaleY = scale; 
sprite.alpha = scale; // 可选 
sprite.x = vanishingPointX + xpos * scale; 
sprite.y = vanishingPointY + ypos * scale; 

 

Z 排序: 
// 假设有一个带有 zpos 属性的 3D 物体的数组 
objectArray.sortOn("zpos", Array.DESCENDING | Array.NUMERIC); 
for(var i:uint = 0; i < numObjects; i++) 

setChildIndex(objectArray[i], i); 

 

坐标旋转: 
x1 = cos(angleZ) * xpos - sin(angleZ) * ypos; 
y1 = cos(angleZ) * ypos + sin(angleZ) * xpos; 
x1 = cos(angleY) * xpos - sin(angleY) * zpos; 
z1 = cos(angleY) * zpos + sin(angleY) * xpos; 
y1 = cos(angleX) * ypos - sin(angleX) * zpos; 
z1 = cos(angleX) * zpos + sin(angleX) * ypos; 

 

3D 距离: 
dist = Math.sqrt(dx * dx + dy * dy + dz * dz); '

 

 

ref:http://www.cnblogs.com/liongis/archive/2010/08/10/1796558.html

Integrating Flex into Ajax applications

Building Ajax applications has proven to be a consistent method for providing engaging applications. However, the explosion in popularity of Adobe Flex cannot be ignored. As we are continually pushed to create the best user experience, we're often faced with the difficult task of integrating Flash-based assets embedded in our Ajax applications. This article discusses the integration of Flash content with existing Ajax content using the FABridge, a code library developed by Adobe to handle this very task.

To be an Ajax developer today is pretty special. We're always at the front lines, ready to greet users and offer the best first impression to the applications we build for them. As Web standards advance and more vendors decide to implement them, our jobs have become easier, allowing us to focus on the user experience. The further advancements in JavaScript frameworks such as Ext JS, jQuery, and Prototype have also allowed us to spend less time worrying about whether our code will work across the platforms we're asked to support, leaving more time to innovate.

Although there are certainly more tools, techniques, and resources available to us today, there is also a shift in development methodology that serves as a push toward the rich world of Flash development. For many shops, the development workflow would involve the user interface (UI) group to produce designs that support a server-side-generated application. With just the JavaScript frameworks we have now, we're pushed in the direction of application development for the client side. However, the emergence of the Flex platform — a free, open source framework for producing Flash applications — brings us further into the application development arena. This type of innovation is good for us on the client side, but we must ensure that we handle the process of integrating it with current architectures in a thoughtful and careful manner.

Before I introduce code samples showing how to work with Ajax and Flex assets, you need to understand the tools and skills required:

  • I produced the Ajax samples in this article using the Ext JS JavaScript library, so you need to download the .zip file that contains the library and supporting documentation.
  • Next, grab a copy of the free Adobe Flex 3 SDK and Adobe Flash Player 9 with debugging capability, if you don't already have it.
  • Although not required to follow along in this article, you may also want to check out at least a trial version of Adobe Flex Builder 3, an Eclipse-based IDE that enables rapid Flex application development in addition to superior debugging and profiling capabilities (see Resources).
  • Finally, a working knowledge of PHP is helpful.

The integration issue

If you were looking forward to replacing all your Ajax content with Flex assets, your task would be much simpler. However, this is an unlikely and often unreasonable approach, because there are many reasons to preserve traditional Ajax functionality. Fortunately, there's no reason you can't keep the best of both environments to produce a rich, cohesive application.

There are quite a few simplistic methods for passing data to ActionScript code from the Flash container (HTML/JavaScript code), including the use of query strings and <param> tags. However, this method is limited to passing data into the container. A more powerful technique is to use the ExternalInterface class, an application program interface (API) used to broker communication between the ActionScript and JavaScript languages. The use of ExternalInterface is best demonstrated by the example in Listing 1:


Listing 1. ExternalInterface example
// ActionScript code
function exposed():String
{
   return "Hello, JavaScript!";
}

ExternalInterface.addCallback( "getActionScript", exposed );

// HTML/JavaScript code
<script language="JavaScript">

var result = flashObject.getActionScript();

</script>

<object id="flashObject" ...>
   <embed name="flashObject" ... />
</object>

Listing 1 demonstrates a stripped-down example of how to use the ExternalInterface class to register an ActionScript function so that JavaScript code can call it. You do this by first defining an ActionScript function, then using the addCallback() method to expose the function to JavaScript for execution. On the HTML side, simply obtain a handle to the Flash container and call the function, which was named using the first parameter to the addCallback() method. Although this demonstration concentrated on exposing functions to the JavaScript code, you can just as easily go the other way by using the call() method of the ExternalInterface class.

The ExternalInterface class can be quite powerful, but there are significant drawbacks to implementing it. To use ExternalInterface, you must be able to write code to implement both the ActionScript and JavaScript environments. This not only requires added skill but double the effort. In this situation, maintaining code as well as two very robust skill sets can become a challenge.

To address the limitations of development against the Flash external API, Adobe has released the FABridge. The FABridge, which ships with the Flex SDK, is a small library used to expose Flash content to scripting in the browser and works in most major browser platforms. With the FABridge, plumbing code that was required to directly implement the Flash external API is now virtually eliminated. Further, the skills required to implement the bridge aren't as robust. As a JavaScript developer, you simply need to be able to understand what's available to you in the way of ActionScript properties and methods. Let's get started with a few examples that demonstrate the capabilities of the FABridge.

An FABridge tutorial

Before you get started using the FABridge, here are the materials and development environment you'll be working with. After downloading the latest Flex SDK, configure the directory structure shown in Listing 2:


Listing 2. Directory structure for the FABridge tutorial
/
+--- bridge
|      +--- fabridge.js
|      +--- fabridge.as
|      
+--- index.html

The directory structure is straightforward: You just have an index page and the FABridge scripts hooked into their own directory named bridge. The location of the FABridge library files depends on your environment. Because I'm using Flex Builder 3 Professional on Mac OS X, my library files reside in install_root/sdks/frameworks/3.0.0/javascript/fabridge/.

Now that you have the appropriate architecture in place, you can begin creating the skeletons on both the HTML/JavaScript and ActionScript sides. Use the code from Listing 3 to develop the HTML/JavaScript skeleton:


Listing 3. HTML/JavaScript skeleton
<html>
<head>
<title>FABridge Tutorial</title>

<script type="text/javascript" src="bridge/FABridge.js"></script>
<script type="text/javascript">
   // ... 
</script>

</head>
<body>
</body>
</html>

As you can see, you simply hook the FABridge JavaScript library to your code, and all the functionality of the bridge is immediately available. Next, use the code from Listing 4 to implement the bridge on the ActionScript side:


Listing 4. Application skeleton
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
       xmlns:bridge="bridge.*"
       layout="absolute"
       width="300"
       height="142">
	   
   <bridge:FABridge bridgeName="flex" /> 
   <mx:TextInput x="70" y="54" id="txt_test" text="FABridge rocks!"/>
   
</mx:Application>

This code might be a bit more unfamiliar to you. The UI is kept clean and simple by defining a single text input control with the ID txt_test and a default value of FABridge rocks! The bridge namespace is defined, and all classes in the bridge directory are imported. Finally, the Flex application is given a name for the bridge to use to access it: flex. To compile this Flex code into a working SWF document, use the mxmlc utility from the Flex 3 SDK. The most basic compile command is shown in Listing 5:


Listing 5. Compiling MXML
path_to_flex_bin_folder/mxmlc path_to_mxml file

The command in Listing 5 compiles the source file and outputs an SWF file with the same file name as the MXML in the same directory. Assuming a successful compilation, you can now hook the resulting SWF into your HTML file, as shown in Listing 6:


Listing 6. Linking the resulting SWF file
<embed src=�main.swf� />

Note: The code in Listing 6 is deliberately light to keep focus on the task of demonstrating the FABridge. Unless you're targeting a specific environment (Listing 6 is targeting Mozilla), you'll want to add more intelligence in the way of object tags and other load scripts.

Assuming that all went well, your application should now look similar to Figure 1:


Figure 1. The sample application
Sample application

Now that you have successfully compiled and linked the Flex application into the HTML container, invoke your first FABridge functions to obtain a reference to the Flex application. Use the code in Listing 7 to fill in the empty <script> tag in your HTML skeleton file:


Listing 7. Obtaining a reference to the Flex application
// global variable, holds reference to the Flex application
var flexApp;  
  
var initCallback = function() {  
   flexApp = FABridge.flex.root();  
   return;  
}  
// register the callback to load reference to the Flex app
FABridge.addInitializationCallback( "flex", initCallback ); 

The code in Listing 7 starts by defining a global JavaScript variable that will hold a reference to the Flex application when the FABridge obtains it. A callback function is defined that sets the global variable and is invoked through the addInitializationCallback() FABridge method. Using this code is simply a matter of matching the name of the bridge that you configured in the Flex application. From here, you're able to access all sorts of ActionScript functionality from the JavaScript code.

Working with ActionScript objects

Now that you've obtained a global reference to the Flex application, you can access ActionScript objects through the consistent interface that the FABridge provides. In the ActionScript world, you would typically access objects through dot notation object.id. Rather than expose ActionScript objects in dot notation, however, the FABridge makes these objects available through function calls. It is a little different at first, but all you need to know is the template to follow. An object traditionally identified in ActionScript as object.id would now be accessed as object.getId(). This is best demonstrated through example: Type the code from Listing 8 into your HTML skeleton to try it out:


Listing 8. Getting ActionScript objects by ID
// get the text input control 
var txt = flexApp.getTxt_test();

The variable txt is an object that represents the text input control with the ID txt_test from the Flex application. You can see the template you would need to follow for gaining access to other ActionScript objects by ID. The declaration begins with the global reference to the Flex application, then a method call that always begins with the string get followed by the ID of the target object. Notice that the name of the ID must begin with a capital letter in this declaration.

Getting and setting the properties of ActionScript objects is similar to the process just used. Keeping up with our example of manipulating the text input control, use the code from Listing 9 to get and set the text property:


Listing 9. Get and set ActionScript properties
alert( "old: " + txt.getText() );
	
txt.setText( "Reset!" );
	
alert( "new: " + txt.getText() );

The code in Listing 9 first alerts the original value of the text input control from the Flex application. By following the template described earlier, you can see that the text property is obtained through a function call, with the get string prepended and the property name camel cased. The set() method uses the same process but accepts a parameter used to configure the new value of the object. After the code in Listing 9 executes, you should see a screen similar to Figure 2:


Figure 2. Setting ActionScript object properties
Setting ActionScript object properties

Now, let's move on to the easiest manipulation of all: calling ActionScript object methods. This process requires no special considerations on your part. ActionScript object methods are used in JavaScript code just as they would be used in ActionScript code. The code in Listing 10 demonstrates the invocation of a method on your text input control:


Listing 10. Invoking ActionScript methods
txt.setVisible( false );

The code in Listing 10 sets the text input control in the Flex application to be invisible. The object can still be referenced and manipulated, it's just not physically visible. Between the ActionScript and JavaScript worlds, this is no change in the way the methods are invoked.

One of the more powerful features of the FABridge is the ability to pass functions between JavaScript and ActionScript code. Check out the code in Listing 11, which dynamically copies the value of the text input in Flex to a <div> on the HTML/JavaScript side:


Listing 11. Passing functions
// define a function used as a callback to JavaScript
var txtCallback = function( event ) {  
   // get the object which fired the event
   var swf_source = event.getTarget();  
   
   document.getElementById( "copy" ).innerHTML = swf_source.getText();
	  
   return;  
}  
txt.addEventListener( "change", txtCallback );

The code in Listing 11 is a JavaScript callback function that's fired each time the text input control value from the Flex application changes. When the value changes, it is copied to a <div> tag with the ID copy. This type of functionality can be very powerful, especially when attempting any sort of integration work between Ajax and Flex content. With both environments relying heavily on events, it's key to be able to have them work together.

The last feature this article explores is exception handling. By default, when you use try . . . catch blocks throughout your JavaScript code, you'll be able to at least access an error code that you can then look up in the online reference for ActionScript errors. This methodology certainly works, but during development, you want access to as much information up front as possible. While using the FABridge, you can get this information simply by installing Flash Player 9 with debugging. With this feature installed, you have access to line numbers, file names, error types, and stack traces. Use the code in Listing 12 to see an example:


Listing 12. Exception handling
try {
   alert( flexApp.throwsAnError() );
}
catch( e ) {
   var msg = "";
   for( var i in e ) {
      msg += i + " = " + e[i];
   }
   alert( msg );
}

An error is thrown from the code in Listing 12 because the method throwsAnError() does not exist. The code from the catch block outputs an alert that looks similar to Figure 3:


Figure 3. Exception data
Exception data

As you can see, this data is far more useful than a single error code and less work to troubleshoot. When you're working with complex integration issues between differing technologies such as JavaScript and ActionScript, you'll appreciate this extra help.


Putting it all together

So far, this article has taken a tutorial-type approach to showing the capabilities of the FABridge. Now it's time to use a real-world scenario to demonstrate its usefulness. As indicated earlier, you want to integrate and use the best of both the Ajax and Flex worlds. One of the components that really shines on the Flex side is its charting capability. Although it's not a free library, it is worth the added cost if you're looking to do some intense client-side application programming. The example you'll work with here is a combination of a PHP service that serves dummy data containing the number of messages received in certain categories for specific users. The data from the PHP service is loaded into a grid control using the Ext JS JavaScript framework, then the same data is pushed over the FABridge as a data provider to a pie chart in Flex. Start by taking at look at the PHP service in Listing 13:


Listing 13. The PHP service
<?php
   $users = array();
   array_push( $users, "Paul" );
   array_push( $users, "Nancy" );
   array_push( $users, "Ned" );
   array_push( $users, "Lucy" );

   $email = array();
   $email[ "email" ] = array();
   $email[ "totalCount" ] = count( $users );
	
   for( $i = 0; $i < count( $users ); $i++ ) {
      $tmp = array();
      $tmp[ "user" ] = $users[$i];
      $tmp[ "friends" ] = rand( 0, 100 );
      $tmp[ "family" ] = rand( 0, 100 );
      $tmp[ "spam" ] = rand( 0, 100 );
      array_push( $email[ "email" ], $tmp );
   }
	
   echo json_encode( $email );
?>

Note: The data in this service is hard coded and only meant to demonstrate the concept.

Next, take a look at Listing 14, which is the MXML to generate the pie chart:


Listing 14. Flex pie chart
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
                xmlns:bridge="bridge.*"
                width="600"
                height="800">
   <bridge:FABridge bridgeName="flex" />
   <mx:Script>
   <![CDATA[    

      [Bindable]
      public var email:Object;
    
      private function displaySpam( data:Object,
                                    field:String,
                                    index:Number,
                                    percentValue:Number ):String {
         var temp:String= (" " + percentValue).substr(0,6);
         return data.user + ": " + '\n' + "Total Spam: " + data.spam + '\n' + temp + "%";
      }
   ]]>
   </mx:Script>


   <mx:Panel title="Spam E-mail">
      <mx:PieChart id="chart" 
                   height="100%" 
                   width="100%"
                   paddingRight="5" 
                   paddingLeft="5" 
                   showDataTips="true" 
                   dataProvider="{email}">          
         <mx:series>
            <mx:PieSeries nameField="user"
                          labelPosition="callout" 
                          field="spam" 
                          labelFunction="displaySpam">
            </mx:PieSeries>
         </mx:series>
      </mx:PieChart>  
      <mx:Legend dataProvider="{chart}"/>
   </mx:Panel>
</mx:Application>

This code was taken from the Adobe documentation and modified to fit the scenario as well as configured for use with the FABridge. One thing to note here is that the variable named email is bindable, which means that any references to this data set will be updated automatically. This works great, because you'll be sending data over the bridge to this same variable, which is then used as the data provider to the pie chart.

The last piece to this puzzle is the JavaScript code in Listing 15:


Listing 15. Produce the grid, populate the chart
<link rel="Stylesheet"
         type="text/css"
         href="../global/ext-2.0.2/resources/css/ext-all.css" />

<script type="text/javascript" src="bridge/FABridge.js"></script>
<script type="text/javascript" src="../global/ext-2.0.2/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="../global/ext-2.0.2/ext-all-debug.js"></script>
<script type="text/javascript">

Ext.onReady( function() {
   // global variable, holds reference to the Flex application
   var flexApp;  
	  
   var initCallback = function() {  
      flexApp = FABridge.flex.root(); 
		
      // load the data store, grid, populate the pie chart from JavaScript
      initUI();
		 
      return;  
   }  

   // register the callback to load reference to the Flex app
   FABridge.addInitializationCallback( "flex", initCallback );
	
   function initUI() {
	
      // create a data store using the PHP service
      var ds_email = new Ext.data.JsonStore(
         {
            url: "service.php",
            root: "email",
            fields: [ "user", "family", "friends", "spam" ]
         }
      );
		
      // when the data store loads, update the pie chart
      ds_email.load( 
         {
            callback: function( r, o, s ) {
               // send an array of objects over the bridge to fill in the pie chart
               var arr_email = new Array();
					
               for( var i = 0; i < r.length; i++ ) {
                  var tmp = new Object();
                  tmp.user = r[i].data.user;
                  tmp.family = r[i].data.family;
                  tmp.friends = r[i].data.friends;
                  tmp.spam = r[i].data.spam;
						
                  arr_email.push( tmp );
               }
					
               flexApp.setEmail( arr_email );	
            }
         }
      );
		
      // create a populate the grid.
      var grid_email = new Ext.grid.GridPanel(
         {
            title: "E-mail Count",
            store: ds_email,
            columns: [
               { header: "User", dataIndex: "user" },
               { header: "Family", dataIndex: "family" },
               { header: "Friends", dataIndex: "friends" },
               { header: "Spam", dataIndex: "spam" }
             ],
             height: 300,
             width: 450,
             renderTo: "grid-email"
         }
      );	
   }
} );

</script>

The first thing to notice about this code are the links to the Ext JS resources needed to make it work. After hooking in the default styles and debug scripts for Ext, an onReady block is configured. This block is executed only after a full Document Object Model (DOM) is ready. You should be familiar with the code used to populate the global flexApp variable with a reference to the Flex application. One addition to the callback is the execution of the initUI function. This function is used to create an Ext data store using the PHP service and to populate an Ext grid control using the resulting data in the store. When the Ext data store is loaded, a data structure is created and pushed over the FABridge so that the data binds as a data provider to the pie chart. The final product is shown in Figure 4:


Figure 4. The final product
Final product

As you scan the data in the grid, it should match up with what's represented in the pie chart. This really is a powerful concept, and you can see the possibilities it has to offer.

Although this was a single real-world example of how you might want to implement the FABridge, there are several other popular ways to use this library. Syncing security information for remote service authentication and techniques to consistently brand and personalize applications are just a couple of examples of how best to use the bridge.


Conclusion

Adobe Flex is an incredible technology that is just starting to reveal its true potential. However, no single product will solve all the wants and needs of developers and users, so it's important that we keep our minds open and explore the possibilities of integration using the FABridge.


Resources

Learn

Get products and technologies

  • Adobe Flex: Visit the Flex product page.
     
  • Ext JS: Download the Ext JS JavaScript framework.
     

Discuss

About the author

Brice Mason

Brice Mason is a husband and father from Albany, New York. He is also a developer, writer, and speaker who frequently starts sentences with "Wouldn't it be cool if . . . ." When not spending time with his family, he can be found writing code and writing about code.

ref:www.ibm.com/developerworks/web/library/wa-aj-flex/#ibm-pcon

flex, component's life-cycle

这篇文章帮了我很大的忙,转了

Earlier today I fixed a minor code issue. It took seconds to identify, but I remember being a little stumped by a similar problem in my early Flex days. The difference now is that I'm familiar with the component life-cycle.

You may think it is only worth reading up on the Flex component life-cycle if you intend to create advanced components, but that's not true, even when you are doing nothing other than extending basic mxml components a little knowledge goes a long way.

To demonstrate the problem take a look at the init method for this simple mxml component called TimeInputBar (which extends Canvas).

 

   
      //<code>Init</code> is called when the component's <code>initialize</code> event is fired:
   
      public var time:Number;
   
       
   
      public function init():void
   
      {
   
          time = 0;
   
      }

That's simple enough. Now take a look at the ActionScript which is creating an instance of the TimeInputBar:

 

   
      var t:TimeInputBar = new TimeInputBar();
   
      t.time = 12;
   
      addChild(t);

Again, simple code, but did you spot the problem? With a little bit of knowledge it's easy to see that time will always be reset to 0 and will never be 12. Why?

When you create a component using the new operator, only part of the life-cycle completes. The component gets as far as the configuration stage, which means you can set properties on the component (to be processed by the component later) but the life-cycle will not go any further than that. It is in effect, paused.

However, all the really cool stuff in the life-cycle, like creating the component's child elements, measuring the component, drawing the component and dispatching events happens during the next stage.

It is only when you add the component to the display list using addChild or addChildAt that the life-cycle continues (in other words ... it continues when the component has a parent).

As mentioned, the next phase is the one in which the cool stuff happens: In more detail, this means that the preinitialize event is dispatched, the component's children are created, the initialize event is dispatched and the component's validation methods are called (those are beyond the scope of this article) and if that's not enough for you, when all that is done then everybody's favourite event, creationComplete is dispatched.

So, with that knowledge in hand let's revisit the order of execution for the original example:

  • Create component using 'new' operator
  • Set time variable to 12
  • Add component to display list
  • initialize event is fired
  • init() method is called
  • time variable is set to 0

Many beginners make the assumption that the preinitialize and initialize events are dispatched early on - don't beat yourself up, that's a reasonable assumption to make. However those events may actually be dispatched after you've set initial values for some of your component's properties.

So, what's the solution? We could simply swap the order of our code:

 

   
      //no worky!
   
      t.time = 12;
   
      addChild(t);
   
       
   
      //worky
   
      addChild(t);
   
      t.time = 12;


...but I'm hoping you can see the issue; components should be just a little more flexible than that!

A perfectly acceptable solution here would be to perform a simple check inside our init method:

 

   
      public var time:Number;
   
       
   
      private function init():void
   
      {
   
          if(isNaN(time)) time = 0;
   
      }


[Edit - it's also perfectly acceptable to set 'time' to 0 when you first declare it - this post is not really concerned with which solution you choose, but rather it uses simplified code to explain why such a problem may arise in the first place.]

Once that is done, it will not matter if you set time before or after you add your component to the display list. If the value is set externally before init is called, the value will not be overridden.

You can read a little more about the Flex component life-cycle in one of my earlier posts here.

ref:nwebb.co.uk/blog/

 

 

Flex 通用调试工具(ff,chrome,ie8+)

如题,写了个很傻逼的调试工具,代码很简单,算是满足我的需求了,需要firebug的支持,chrome可以用firebuglite. 至于ie,需要ie8的开发人员工具.好了 上代码

 

package ifree.common.Logging
{
	import flash.external.ExternalInterface;
	public class Logger
	{
		
		public function log(msg:String):void{
			ExternalInterface.call("console.log",msg);
		} 
		public function info(msg:String):void{
			ExternalInterface.call("console.info",msg);
		} 
		public function error(msg:String):void{
			ExternalInterface.call("console.error",msg);
		} 
		public function debug(msg:String):void{
			ExternalInterface.call("console.debug",msg);
		} 
		public function warn(msg:String):void{
			ExternalInterface.call("console.warn",msg);
		} 
		public function _trace(msg:String):void{
			ExternalInterface.call("console.trace",msg);
		} 
	}
}

 

不要扔砖头

Flex的MXML文件结构

       下面是一个MXML

<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx=http://www.adobe.com/2006/mxml layout="absolute">

   

</mx:Application>

 

第一行声明XML文件采用的语法版本号和文件采用的编码格式。mx:Application标签是一个特殊的标签。在每一个MXML文件,但作为程序入口的运行文件只有一个,主文件的标示是根节点为mx:Application,一个程序中出现一个mx:Application节点。还有一个属性xmlns:mx=http://www.adobe.com/2006/mxml表示将mx定义为XML的命名空间。xmlns标签专门用来定义XML的命名空间,XML命名空间可以用来定义一套独立的XML标签,并且为这些标签指定特殊的解析方式。比如XML文件中默认的标签格式为:<Button>node</Button>,这里的Button节点作为一个普通的文本节点,没有特殊的意义。定义命名空间后,在节点上加上空间前缀:<mx:Button></mx:Button>这时候就代表mx空间下的Button对象。

Mx命名空间对应的路径是”http:// www.adobe.com/2006/mxmlFlex的配置文件中将这个路径定义为一个全局资源标识符,并对应了一个XML文件。在这个文件中,列出了mx命名空间下的所有标签。在Flex SDK3.0.1 目录下的frameworks目录中找到flex-config.xml文件,打开并找到如下内容:

 

<namespaces>

     <namespace>

            <uri>http://www.adobe.com/2006/mxml</uri>

            <manifest>mxml-manifest.xml</manifest>

     </namespace>

</namespaces>

 

从上面可以发现,http://www.adobe.com/2006/mxml”这个URImxml-manifest.xml文件对应,打开该文件,该文件列出了MXML中的所有标签与标签关联的类文件路径。

<?xml version="1.0"?>

 

<componentPackage>

 

   <component id="FileSystemComboBox" class="mx.controls.FileSystemComboBox"/>

<component id="FileSystemDataGrid" class="mx.controls.FileSystemDataGrid"/>

      。。。。。。。

<component id="WebService" class="mx.rpc.soap.mxml.WebService"/>

<component id="WebServiceOperation" class="mx.rpc.soap.mxml.Operation"/>

 

</componentPackage>

 

 

在开发中,当程序有很多MXML文件和AS文件时,为了方便调用,我们可以将功能相似的文件放在一个文件夹中,定义一个命名空间在定义命名空间时,为了方便,很一般直接指定命名空间包括的标签路径。比如:

xmlns:myComp=”components.*”

上面使用了通配符”*” components目录下所有的MXML文件个ActionScript类文件都被包括在myComp命名空间下。例如components中有一个Loginpanel.mxml,则程序中调用这个文件时,代码如下

<myComp: Loginpanel></myComp: Loginpanel>

myComp下的标签被自动指向components文件,当标签数量较多而且分布在不同文件夹时,可以效仿Flex配置文件的做法,使用XML文件来描述。

ref:hi.baidu.com/flexok/blog/item/83397ca93c70dc044a36d61b.html