开发者

How do I call a method from a different class in my current class. AS3

I have a class, my document class, called SilkRoadTweeter.as I also have a class called User.as In my User class I need to call 开发者_高级运维a method called nonce() I have tried this,

trace(SilkRoadTweeter(root).nonce());

But I get the error,

TypeError: Error #1009: Cannot access a property or method of a null object reference.


You said that the nonce() function is in the SilkRoadTweeter class and you need to call it from the User class. You must have a reference to the SilkRoadTweeter in order to call functions on it. The error is saying it doesn't know what a SilkRoadTweeter is. Using root to get a reference is messy in my opinion and should be avoided. I would suggest passing a reference to the User class when you create it. If that is not an option, making the function nonce() on the SilkRoadTweeter class static would solve your problem, so long as the function doesn't need to access non-static properties of the SilkRoadTweeter. You said all it does is return a generated number so I would guess it doesn't need to access non-static properties. I can elaborate further on what I've said if your still confused.


Edit

I actually forgot one of the most important one, you could dispatch en event!

     //In the Document class
     var user:User = new User();
     user.addEventListener( "nonce" , nonceEventListener );

     //define your listener
     private function nonceEventListener(event:Event):void
     {
        user.result = this.nonce();
     }

     //In the User class
     public function result(value:Number):void
     {
        //here you deal the generated Number
      }

      //somewhere in the Class
     this.dispatch( new Event("nonce") );

End of Edit

You should pass your instance of SilkRoadTweeter in the User class

For instance:

    //In the Document class
    var user:User = new User( this );

    //In the User class
    var srt:SilkRoadTweeter;

    public function User( srt:SilkRoadTweeter )
    { 
       this.srt = srt;
       srt.nonce();
    }

If the User class instance is added as a child of the SilkRoadTweeter class, you could also do this

    //In the User class
    var srt:SilkRoadTweeter;

    public function User()
    { 
        addEventListener(Event.ADDED , addedListener );
    }

    protected function addedListener(event:Event ):void
    {
         srt = this.parent as SilkRoadTweeter;
         srt.nonce();
    }


In this case "root" is probably null. Try debugging it to check.


try:

trace(root is SilkRoadTweeter)

I have feeling you need to do:

trace((root.getChildAt(0) as SilkRoadTweeter).nonce());
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜