开发者

Catching the right event with the right listener?

Consider this scenario we have a class A which is singleton it has a function Sum(a,b) ** . Now we have two classes **Class B and Class C respectively. Both classes (B,C) call add function and listen for a event.

Class A
{
    function add(a:int,b:int):void
    {
        c:int = a+b;
        dispatchEvent(new myEvent(myEvent.addComplete,c));
    }

}

Class B
{
    function addSomething():void
    {
          var objectA:A = new A();
          objectA.addEventListener(myEvent,onAddComplete);
          var a:int = 10;
          var b:int = 20;
          objectA.add(a,b); 
    }

    function onAddComplete(e:myEvent):void
    {
              trace(e.something);
     }
}

Similarly there is a C and D class. Now when lets say both classes call A's add function (when A is singleton) how does one insure that the right answer is returned to the right listener.

Secondly what if the calls are changing something, is there a locki开发者_开发技巧ng in singleton?


When you instantiate a Singleton, you don't use "new" , otherwise it wouldn't be a Singleton, you would keep creating instances of the A class. In order for your class to be a Singleton, only one instance can be created, this way , when you call A in other classes, you are calling the same instance of A.

Generally you use the getInstance method which either return an instance of the Singleton class if none exist or return the previously created instance of A.

Have a look at this for more information: http://www.gskinner.com/blog/archives/2006/07/as3_singletons.html

It is generally accepted that Singleton should be avoided when possible. You should find a few posts here explaining why, here's an example:

What is so bad about singletons?

In your example, you could do this for instance:

class A
{
   function add( params:Object , dispatcher:EventDispatcher )
    { 
       c = params.a + params.b;
       dispatcher.dispatchEvent( new MyEvent(c) );
  }
}

class B
{
    private var _dispatcher:EventDispatcher = new EventDispatcher();

    function addSomething():void
    {
          var objectA:A = new A();
          _dispatcher.addEventListener(MyEvent.ADD,onAddComplete);
          var params:Object = {a:10 , b:20};
          objectA.add(params , _dispatcher); 
    }

    function onAddComplete(e:MyEvent):void
    {
              trace(e.something);
     }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜