问题
I moved my code from my Application to a separate AS class file and now I'm getting the following errors:
1061: Call to a possibly undefined method addEventListener through a reference with static type Class.
1180: Call to a possibly undefined method addEventListener.
.
package managers {
import flash.events.Event;
import flash.events.EventDispatcher;
public class RemoteManager extends EventDispatcher {
public function RemoteManager() {
}
public static function init(clearCache:Boolean = false):void {
addEventListener(SETTINGS_CHANGE, settingChangeHandler);
addEventListener(ITEMS_UPDATED, itemsUpdatedHandler);
}
}
}
回答1:
Your code
addEventListener(SETTINGS_CHANGE, settingChangeHandler);
evaluates to
this.addEventListener(SETTINGS_CHANGE, settingChangeHandler);
There is no this in a static method, since it's designed to function without an instance. Furthermore, you cannot attach an event listener and dispatch events from a static class.
Either change your function declaration to
public function init(clearCache:Boolean = false):void
Or implement a singleton pattern to kinda get a "static class, that dispatches events".
Singleton with event management.
回答2:
You have declared your method init as static , so all you can use into this one is static field, static method, no object that belong to the instance.
Remove the static from the function or try to implements a singleton if it what you are after.
here a quick really simple one :
public class RemoteManager extends EventDispatcher {
private static var _instance:RemoteManager;
public function static getInstance():RemoteManager{
if (_instance == null) _instance=new RemoteManager();
return _instance;
}
public function RemoteManager() {
if (_instance != null) throw new Error("use getInstance");
}
public static function init(clearCache:Boolean = false):void {
getInstance().addEventListener(SETTINGS_CHANGE, settingChangeHandler);
getInstance().addEventListener(ITEMS_UPDATED, itemsUpdatedHandler);
}
}
// use it
RemoteManager.init();
来源:https://stackoverflow.com/questions/11826131/getting-error-type-1061-call-to-a-possibly-undefined-method-addeventlistener-th