Given the following code:
Class CEvent:
public class CEvent extends Event
{
public static const TYPE:String = "cEvent";
private var m_strCode:String;
public function get code():String
{
return m_strCode;
}
public function CEvent(pCode:String, bubbles:Boolean=false,
cancelable:Boolean=false)
{
super(TYPE, bubbles, cancelable);
m_strCode = pCode;
}
}
Class A:
dispatchEvent(new CEvent(MY_CONST))
Class B:
m_a = new A();
m_a.addEventListener(CEvent.TYPE, onCEvent);
.
.
.
private function onCEvent(pEvent:CEvent):void
{
switch (pEvent.code)
{
case A.MY_CONST:
dispatchEvent(pEvent);
}
}
Class C:
m_b = new B();
m_b.addEventListener(CEvent.TYPE, onCEvent);
.
.
.
private function onCEvent(pEvent:CEvent):void
{ // breaks right here
}
I get this error when it breaks on class C, after dispatching it originally from Class A:
Error #1034: Type Coercion failed: cannot convert flash.events::Event#9861089 to
<path>.CEvent.
This doesn't seem to make a lot of sense, and it seems to be going completely against the way inheritance works. Even if there were code in Adobe's implementation of dispatchEvent() that specifically goes through and shaves off anything that's been added through inheritance and just dispatches a "normal" Event instance, that should cause it to break in class B, not C.
Could someone please explain? Thanks.
Edit: By the way changing class B's code to do this instead makes everything work just fine:
dispatchEvent(new CEvent(pEvent.code));
I still need to understand what the issue is though. Thanks.
The error occurs because you have not implemented the clone() method in your custom event.
When you re-dispatch an event (in your Class C), Flash clones the event instead of just re-dispatching the original event.
The event that is re-dispatched therefore is a plain old Event object, because that's what the default clone() method returns.
In general, you should always implement a clone() method for your custom events. It's pretty straight forward to do. In this case it should look something like this:
override public function clone():Event
{
return new CEvent(m_strCode, bubbles, cancelable);
}
Related
I have this situation where I declare inside my main class a function that looks like this:
public class Main extends MovieClip
{
public static var instance:Main;
public function Main()
{
// constructor code
welcomeScreen();
instance = this;
}
public final function welcomeScreen():void
{
//some code in here
}
public final function startLevelOne():void
{
//some other code here
}
}
In some other class I use this statement to fire a reset:
restart.addEventListener('click', function() {
Main.instance.welcomeScreen();
});
Somehow in another class I try to use the same statement for 'startLevelOne' but it seems it is not working and gives the fallowing error:
1195: Attempted access of inaccessible method startLevelOne through a reference with static type Main.
Any ideas?
UPDATE #1
The class where I try to access the function is in full this one:
public class LevelBrief extends MovieClip
{
public function LevelBrief()
{
// constructor code
startBut.addEventListener('click', function() {
Main.instance.startLevelOne();
});
}
}
UPDATE #2
I have pasted the full code of the main definition here http://pastebin.com/s6hGv7sT
Also the other class could be found here http://pastebin.com/s6h3Pwbp
UPDATE #3
Even though the problem was solved with a workaround, I still cannot understand where was the problem.
I would recommend to leave the static instance (singleton), and work event-based. Now you make all functions public, which is not desirable. It's not that hard to use custom events. See this is how your Main class could look:
public class Main extends MovieClip
{
public function Main()
{
this.addEventListener(Event.ADDED_TO_STAGE, handleAddedToStage);
}
public function handleAddedToStage(event:Event)
{
this.removeEventListener(Event.ADDED_TO_STAGE, handleAddedToStage);
this.showWelcomeScreen();
stage.addEventListener(ScreenEvent.SHOW_WELCOME_SCREEN, handleScreenEvent);
stage.addEventListener(ScreenEvent.SHOW_LEVEL, handleScreenEvent);
}
private function handleScreenEvent(event:ScreenEvent):void
{
switch (event.type)
{
case ScreenEvent.SHOW_WELCOME_SCREEN:
{
this.showWelcomeScreen()
break;
}
case ScreenEvent.SHOW_LEVEL:
{
// event.data contains level number
this.startLevel(event.data);
break;
}
default:
{
trace("Main.handleScreenEvent :: Cannot find event.type '" + event.type + "'.");
break;
}
}
}
private function showWelcomeScreen():void
{
trace("show WelcomeScreen")
//some private code in here
}
private function startLevel(level:int):void
{
trace("start level: " + level)
//some other private code here
}
}
This is how the custom event class should look (ScreenEvent.as). Note it has an optional parameter called data. You can pass any value (objects, numbers, strings etc) into this. To the example as clear as possible, I used one event-class for both actions, you can also choose to make more specific custom events for other actions with more detailed parameters, you would have names like ScreenEvent, LevelEvent, PlayerEvent, GameEvent etc etc..
At the top of the class the (static constant) types are defined. An event should only have getters.
package
{
import flash.events.Event;
public class ScreenEvent extends Event
{
public static const SHOW_WELCOME_SCREEN:String = "ScreenEvent.showWelcomeScreen";
// event.data contains level number
public static const SHOW_LEVEL:String = "ScreenEvent.showLevel";
private var _data:String;
public function ScreenEvent(type:String, data:String):void
{
super(type);
this._data = data;
}
public function get data():String
{
return this._data;
}
override public function clone():Event
{
return new ScreenEvent(this.type, this._data);
}
}
}
.. Anywhere in your code you can dispatch the event to the stage.
// dispatch event to Main (stage). Should show welcome screen in our case
stage.dispatchEvent(new ScreenEvent(ScreenEvent.SHOW_WELCOME_SCREEN));
// show level 2
stage.dispatchEvent(new ScreenEvent(ScreenEvent.SHOW_LEVEL, 2));
I know, its a bit more code, it looks more difficult at first but if the project grows, it will help a lot. The difference with events is 'this could happen, and when it happens, do this' instead of 'do this here, do that over there'
The advantage is that if you remove the event listener in the Main class, nothing will break (loosely coupled). This makes it easier to maintain, it saves a singleton, and you have the ability to extend the Main class if you want to.
I think you wrote
Main.startLevelOne();
instead of
Main.instance.startLevelOne();
Hmm. Given your code, there is only one serious question - what is PerwollGame? You have there public static var instance:PerwollGame; and you assign it an object of type Main. Perhaps that PerwollGame has a startLevelOne() function with a different signature, that obscures your function in the Main class. Also, the other people who answered you are right as well, you should never use nested functions in your code, really put that listener of yours out from inline declaration.
Judging from your coding style and the error reported, I would assume you did this.
public static function startLevelOne():void
There is a fine line between static methods and instantiated objects.
Also never use nested functions
public class LevelBrief extends MovieClip
{
public function LevelBrief()
{
// constructor code
startBut.addEventListener('click', onMyClick )
}
public functiononMyClick (e:Event) {
Main.instance.startLevelOne();
});
}
}
I assume that when you register the listener Main.instance is not already assigned.
Did you try to trace Main instance here?
public function LevelBrief()
{
// constructor code
startBut.addEventListener('click', function() {
Main.instance.startLevelOne();
});
trace(Main.instance); // I assume Main.instance is null
}
what about if you add the listener in another method in LevelBrief like :
public function registerListeners():void{
trace("Main.instance == null? -> " + (Main.instance == null)); //not null here if called later.
startBut.addEventListener('click', function() {
Main.instance.startLevelOne();
});
}
I get some weird errors when creating CustomEvent, it appears Event being extended does not give access to Event properties:
package
{
import flash.events.Event;
public class CustomEvent extends Event
{
//public static const COMPLETE:String = 'complete';
private var _assetName:String;
public function get assetName ():String
{
return _assetName;
}
public function set assetName ( aname:String ):void
{
_assetName = aname;
}
public function CustomEvent (type:String, bubbles:Boolean = false, cancelable:Boolean = false)
{
super (type, bubbles, cancelable);
}
public override function clone ():Event
{
return new CustomEvent(type, bubbles, cancelable) as Event;
}
}
}
When doing:
myObj.addEventListener(CustomEvent.COMPLETE, objLoaded);
I get error that COMPLETE doesnt exist... Ok, i set it to the place and then it caomplains about cannot convert CustomEvent to Event.
What am i missing here ??
You need to declare this public static const COMPLETE:String = 'complete'; as static var/const are not transfered to extending classes.
The error about converting CustomEvent to Event may be caused by setting event listener to listen to the Event not CustomEvent.
Where is the event dispatched and what does the signature of the listener look like?
We've got a few issues to cover here:
You have your public static const COMPLETE... commented out. Why? That's needed if you want to refer to CustomEvent.COMPLETE as the event type.
Using my psychic third eye, you've got your event listener declared like this:
public completeListener(evt:Event):void
...
That's not going to work the way you want it to. You need
public completeListener(evt:CompleteEvent):Void
...
Unrelated to the compilation issue, your custom event has another issue. Your clone method is not going to clone the assetName property. Try something like this:
public override function clone():Event
{
var ret:CustomEvent = new CustomEvent(type, bubbles, cancelable);
ret.assetName = assetName;
return ret;
}
I would like to extends the Event class to add some events I am using in game.
But I don't want the new Event Class to have the old public static types..
For instance I don't want to have:
NewEventClass.ENTER_FRAME
How do you go about extending the Event class without getting the old types mixed in?
Is there any way to outsmart AS3 to leave out the uneeded types?
Or should I avoid creating a new Event type altogether and just add the new strings?
Extending Event is only really necessary if you want to add some extra properties to it, for example:
public class EnemyEvent extends Event
{
// Constants used to represent event type
public static const ENEMY_KILLED:String = "killed";
// Event properties
public var score:int = 0;
/**
* Constructor
* Retain Event behaviours
*/
public function EnemyEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false)
{
super(type, bubbles, cancelable);
}
}
So that when you dispatch this event from an enemy you can go:
var evt:EnemyEvent = new EnemyEvent(EnemyEvent.ENEMY_KILLED);
evt.score = myScoreValue;
dispatchEvent(evt);
And then make use of the score property from the listening method within the game engine:
enemy.addEventListener(EnemyEvent.ENEMY_KILLED, _countKill);
function _countKill(e:EnemyEvent):void
{
gameTotalScore += e.score;
if(gameTotalScore > 100) getAchievement();
e.target.removeEventListener(e.type, _countKill); // <-- woudn't work without extending event either
}
If you just need to store constants to use in addEventListener(x, ..), new Event(x), etc then you can just make a class that holds these and doesn't have anything to do with Event:
public class CustomEvents
{
public static const MY_CUSTOM_EVENT:String = "myCustomEvent";
}
So that you can just use these as needed:
new Event(CustomEvents.MY_CUSTOM_EVENT);
addEventListener(CustomEvents.MY_CUSTOM_EVENT, _listener);
The former method is still preferable as it's tidier and more logical.
Additionally; your note about your custom event having constants such as ENTER_FRAME isn't the case anyway, because they are static and belong to Event. You'll get this error if you try access ENTER_FRAME through the example in your answer:
1119: Access of possibly undefined property ENTER_FRAME through a
reference with static type Class.
using robotlegs i always retrieve this error. I have not idea whats wrong.
TypeError: Error #1009: Cannot access a property or method of a null
object reference.
at org.robotlegs.mvcs::Actor/dispatch()[/Users/shaun/Documents/
Development/Workspaces/GanymedeFB4/robotlegs-framework/src/org/
robotlegs/mvcs/Actor.as:57]
Model
package com.something.model {
// someimports
public class PhotoModel extends Actor {
public function uploadAndDetect() : void {
// something
dispatch(new DetectEvent(DetectEvent.DETECTED));
}
}
}
Event
package com.something.events {
// someimports
public class DetectEvent extends Event {
public static const DETECTED : String = "DETECTED";
public function DetectEvent(type:String, bubbles:Boolean = false, cancelable:Boolean = false){
super(type, bubbles, cancelable);
}
override public function clone():Event{
return new DetectEvent(type, bubbles, cancelable);
}
}
}
I can't read German well enough to be sure, but I'd suspect that the issue is that your Model isn't getting injected with the Event Bus (IEventDispatcher shared by just about everything Robotlegs needs to communicate with).
How are you instantiating this? Are you running this from a Unit test? If so, you need to set the eventDispatcher on your Model. If not, you need to use mapClass, mapSingleton, or mapSingletonOf to make sure your Model gets instantiated with the things it needs to work as an Actor.
When and where are creating the Model? I bet that your are not injecting its dependencies.
The model should be created in a Command and the use:
var model: PhotoModel = new PhotoModel();
injector.injectInto(model);
And then the eventDispatcher (the only dependency of Actor) should be injected.
What I am trying to do is kind of odd, but I am wondering if anyone can come up with a clever way to do what I want to do. Basically, I want to re-define a named function at runtime. I can do this with anonymous functions, but I can't figure out a way to do it for named functions. I want to do this so that I can implement a "spy" functionality on an object for a testing framework (a port of Jasmine to Flex).
Take, for instance, this class:
public class TestClass
{
public var anonymous:Function = function():void {
trace("original anonymous");
};
public function named():void {
trace("original named");
}
}
I can easily re-define the anonymous function because it is just a variable. Javascript uses this idiom a lot.
var testClass:TestClass = new TestClass();
testClass.anonymous = function():void { trace("overridden anonymous"); }
BUT, when I do the same thing for named functions, you get a compile-time error:
// Does not compile
testClass.named = function():void { trace("overridden named"); }
I tried to make it a bit more "squishy" but this leads to a runtime failure "Cannot assign to a method named on TestClass".
// Compiles with runtime failure
testClass["named"] = function():void { trace("overridden named"); }
Can anyone more clever than I come up with a way to hack this? Can the bytecode be hijacked? Something?
I want to modify an object, not a
class
But object doesn't contain functions, only non-static variables. I tried to use prototype property and replace method there, but original method still gets called instead of injected one.
About "hack" bytecode, do you mean "hack" already loaded SWF in runtime? I think it's not possible. I'm sure, though, you can parse SWF with something like as3swf, find method in bytecode, replace it and save result in new SWF.
I had an idea bout making a function "cache" . This might work with what you need.
Let's say you have a class "Car" with a method you need to redefine at runtime:
public class Car extends Sprite
{
private var functionCache:Function;
public function Car()
{
super();
}
public function flexibleFunction(functionBody:*=null):void{
if(functionBody is Function){
functionBody.call();
functionCache=functionBody;
} else {
functionCache(functionBody);
}
}
}
Usage:
public class Main extends Sprite
{
private var car:Car;
public function Main()
{
car = new Car();
car.flexibleFunction(function(){trace("redefine test #1")});
car.flexibleFunction();
car.flexibleFunction(function(doParametersWork:String="let's see"){trace("redefine test #2: " + doParametersWork);});
car.flexibleFunction("yes they do");
car.flexibleFunction();
}
}
an easy way to accomplish what you want is to simply pass a new function to the original function and execute it from there:
package
{
//Imports
import flash.display.Sprite;
//Class
public class RedefineFunction extends Sprite
{
//Constructor
public function RedefineFunction()
{
originalFunction();
originalFunction(redefinedFunction);
}
//Original Function
public function originalFunction(redefinition:Function = null):void
{
if (redefinition != null)
redefinition();
else
trace("Original Function Definition");
}
//Redefined Function
private function redefinedFunction():void
{
trace("Redefined Function Definition")
}
}
}
traces:
Original Function Definition
Redefined Function Definition