ActionScript3.0中类间传值问题解决
做的东西需要自己封装一个HttpService的操作类,传入url和提交的参数,返回ArrayCollection。参照Flex sample中的photoView(图片浏览器)的Http操作写了个类,却发现它无法在类与类之间传值。
一开始我的代码是这样的:
{
import flash.events.*
import mx.collections.ArrayCollection;
import mx.collections.IViewCursor;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;
import mx.utils.ArrayUtil;
public class ResultService
{
private var service:HTTPService;
public var Result:ArrayCollection;
public function ResultService(url:String,obj:Object)
{
service = new HTTPService();
service.url = url+"?"+Math.random();
service.method=Constants.REQUEST_METHOD;
if(obj.action==Constants.READ)
{
service.addEventListener(ResultEvent.RESULT, resultHandler);
}
service.send(obj);
}
private function resultHandler(event:ResultEvent):void
{
[color=Red]Result = event.result.resp.catagory;[/color]
}
}
}
我却无比郁闷地发现,在红色Result = event.result.resp.catagory我可以trace出Result的值,但是在其它类引用Result的时候它却是null。这个问题已经是第二次出现了,上次是让雨用一个巧妙的方法给解决了,这次得老老实实解决它。
多次trace以后,把问题定位在了数值的作用域中。莫非,Result得到的是一个引用,而不是一个值?查阅flex帮助,event.result返回的是一个ArrayCollection,顺理成章赋值给Result不是很舒坦吗...问题就在这里了..这个Result得到的是对event.result.resp.catagory的引用。离开了resultHandler这个函数,event.result.resp.catagory也不复存在,Result所指向的对象变成了空(null),因此trace出来的东西也只会是null了。
既然明白了是引用的问题,跟着要做的事情就很好解决了。我们要给Result赋值。ArrayCollection有一个addItem的方法,我只要利用它,就能把Result充实了,它也不会再是null了。Result可以在其它类调用了。
修改后的代码如下:
{
import flash.events.*
import mx.collections.ArrayCollection;
import mx.collections.IViewCursor;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;
import mx.utils.ArrayUtil;
public class ResultService
{
private var service:HTTPService;
[color=Blue]public var Result:ArrayCollection = new ArrayCollection();[/color]
public function ResultService(url:String,obj:Object)
{
service = new HTTPService();
service.url = url+"?"+Math.random();
service.method=Constants.REQUEST_METHOD;
if(obj.action==Constants.READ)
{
service.addEventListener(ResultEvent.RESULT, resultHandler);
}
service.send(obj);
}
private function resultHandler(event:ResultEvent):void
{
var result:ArrayCollection = event.result.resp.categories.category is ArrayCollection
? event.result.resp.categories.category as ArrayCollection
: new ArrayCollection(ArrayUtil.toArray(event.result.resp.categories.category));
var temp:ArrayCollection = new ArrayCollection();
var cursor:IViewCursor = result.createCursor();
while (!cursor.afterLast)
{
Result.addItem(cursor.current);
cursor.moveNext();
}
}
}
}
但是这样,大家请看蓝色那段的代码..必须早期实例化了Result才能给它赋值,这是个相当危险的做法,严重影响了类的可扩充性。同时我也不知道应该要如何写这个类才能让它更好地工作。如果我要处理相当多不同的e4x数据,用switch是绝对不明智的。到时候可能用工厂模式来设计...或者直接写N个处理Http数据的类,写成static方法....发心得的同时,请求指教,我应该如何设计这个HttpResult类?
原来所谓的类间传值不能只是因为我所请求的数据为空而已……而且我居然没有意识到这个问题……因为当时Trace的时候是A类可以获得数据而B类不能获得的。FlashSeer的版主很耐心地回答了我的问题。解决办法就是,使用监听器。
AS3中一个重大的改动就是完善了事件模型。一切异步的数据操作通过事件来进行实在是太好不过了。同时,AS3中的Object是一个很好的数据载体,适当使用的话可以简化相当多的操作。
今天(两天内三次重构)把一些关键的操作代码等等写了出来,离胜利又前进了一步~猫粮加油..可能会在10月中旬再重构一次项目的代码..到时候代码的质量又会再有一个提高吧。