is it ok to call removeEventListener() twice? - actionscript-3

private function saveDatabase(obj:Object):void{
database.setValue(obj);
database.addEventListener( DatabaseReferenceEvent.VALUE_CHANGED, dbValueChanged );
}
private function dbValueChanged(event:DatabaseReferenceEvent):void {
database.removeEventListener( DatabaseReferenceEvent.VALUE_CHANGED, dbValueChanged );
//do something here
}
private function destroy():void{
database.removeEventListener( DatabaseReferenceEvent.VALUE_CHANGED, dbValueChanged );
// remove all other objects
}
In the above code sometimes due to latency issues, the value changed event may not get triggered. So while calling destroy() I am not sure if the event listener is removed or not? Is it ok to call it in destroy() even if it's removed in dbValueChanged();

If it is of concern and you think there could be multiple listeners as Organis suggests you can check to see if the listener exists.
flash as3 check event listener

Related

"Warning: 1090: Migration issue" despite explicitly registering event handlers

I have a game engine class that inherits from MovieClip and handles mouseDown events in a private instance method. For the sake of simplicity, I name the event handler onMouseDown. It looks like this:
private function onMouseDown(e:MouseEvent):void
{
if (_isEnginePlaying)
{
_player.attack();
}
}
I register it in the engine class's init method (itself an addedToStage handler) that looks like this:
private function init(e:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// ...
stage.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
// ...
}
This compiles and works correctly, but the compiler warns:
Warning: 1090: Migration issue: The onMouseDown event handler is not triggered automatically by Flash Player at run time in ActionScript 3.0. You must first register this handler for the event using addEventListener ( 'mouseDown', callback_handler).
But, as shown, I did register the handler using addEventListener(). Why does the compiler still emit this warning and what can I do to make the warning go away?
This is because the handler was registered with a different instance and not the game engine instance (this). Remember that event handlers in AS2 were registered simply by specifying them as properties on the instances that should handle the respective events and will automatically fire when needed. The warning is there to inform the developer that they do not automatically fire in AS3.
So the compiler errs on the side of caution, assumes I'm trying to register a click handler with the game engine instance (even though I've already registered it with the stage) and warns me to that effect.
There are a number of ways to make the warning go away:
Just rename the onMouseDown handler. The "on-" convention is a holdover from AS2 and the compiler only emits warnings for handlers following this naming convention; if you're comfortable settling for a different convention, this is the recommended solution. The convention used at Adobe is "-Handler" (sources 1 2 3), so onMouseDown becomes mouseDownHandler:
private function init(e:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// ...
stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
// ...
}
private function mouseDownHandler(e:MouseEvent):void
{
if (_isEnginePlaying)
{
_player.attack();
}
}
If this can listen for the event, register the event with this instead:
private function init(e:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// ...
addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
// ...
}
If the intention was for this to listen for the event, then registering the handler with a different instance was inappropriate.
If you need to register the handler with a different instance, but you're sure that the definition is where it should be, you'll have to rename the handler. If for whatever reason changing the naming convention across all of your event handlers is not an option, the least you should do is prefix the name of whatever you're registering it with, so it's clear that this handler is not intended to be registered with this, but with a different instance:
private function stage_onMouseDown(e:MouseEvent):void
{
if (_isEnginePlaying)
{
_player.attack();
}
}
If you insist on keeping things the way they are, you can suppress the warning altogether, but obviously this is not something you should be doing unless you have a very good reason to.

Robotlegs - second dispatch does not work with addViewListener

I have a mediator created in Robotlegs, and its related view would dispatch two different kinds of events. When the mediator captures the event, it would just simply dispatch the event. The problem I ran into was that the first event is re-dispatched flawlessly, but the 2nd event was not dispatched.
However, if I manually assign a different handler to the 2nd event, the event is properly captured.
Below is the relevant code:
public class MyMediator extends Mediator
{
[Inject]
public var view:MyView;
public override function onRegister():void
{
super.onRegister();
addViewListener( SomeEventTypeA.COOL_EVENT, dispatch, SomeEventTypeA ); // This event is dispatched correctly
addViewListener( SomeEventTypeB.STUCK, dispatch, SomeEventTypeB ); // This one is not correctly dispatched
//A twist, if I uncomment the following code, the event is captured by its handler
//addViewListener( SomeEventTypeB.STUCK, view_stuck, SomeEventTypeB );
}
private function view_stuck( event:SomeEventTypeB ):void
{
//ah ha, this is called correctly if the above relevant line is uncommented
}
}
Found the cause:
The event needs to have a proper clone method in order to be re-dispatched correctly. See related link:
http://knowledge.robotlegs.org/kb/application-architecture/why-doesnt-my-event-trigger-the-command-it-is-mapped-to

Add EventListener to function?

Quick question... Is is possible to attach an EventListener to a function? Such that if at any point in a function's execution an Event is Dispatched the EventHandler will get fired?
Cheers.
You can use the stage to dispatch such an event and listen to it:
stage.addEventListener("myFunctionWasCalled", callback);
myFunction();
public function callback(event:Event):void {
trace("callback executed");
}
public function myFunction():void {
stage.dispatchEvent(new Event("myFunctionWasCalled"));
}
Event listeners are attached to objects that belong to a class that descends from EventDispatcher. You cannot attach them to a function.
You can achieve this by simply passing a function reference (callback) as an argument
function cb(s:String):void {
trace(s);
}
function doit(f:Function):void {
// do something
f("Hi");
// do some more stuff
}
doit(cb);
If you only want to listen for a event in the lifetime of a function call just add/remove as needed.
example:
function somefunction():void{
someobject.addEventListener(Event, eventhandler);
... doing stuff
someobject.removeEventListener(Event, eventhandler);
}
Now keep in mind if your doing this then your choice in even flows may become very hard to track down the road.
Typicality you only really need to worry about this in the life and death of a object vs the life and death of a function call.
To attach an event listener to an object this object must implement IEventDispatcher interface. So you could extend Function class and add your methods. AS3 docs say that Function is not final, but AS3 compile disagrees with it: VerifyError: Error #1103: Class Bla cannot extend final base class.
So, the short answer is: you can't attach an event listener to a function.
But as it was already mentioned you could:
Pass callback/callbacks to the function which will be called at some point: function bla(callback1:Function, callback2:Function):void.
Dispatch events from some other object during function execution, for example you could make a Functor class which has method execute() and implements IEventDispatcher. In this way you'd call the function myFunctor.execute() and could get dispatched events.

remove ENTER_FRAME EventListener from inside this as3

This is my code in Flash/AS3, in main class.
addEventListener(Event.ENTER_FRAME,function(e:Event){
if(findObject == true){
// I want to remove this ENTER FRAME
}
});
try this:
e.currentTarget.removeEventListener(e.type, arguments.callee)
You shouldn't be doing what you do in the code above.
The mgraph's code has a tiny chance of failing to work as advertised if the currentTarget of the event doesn't have a removeEventListener() method (possible, but very unlikely). From the compiler standpoint though you will be trying to dynamically resolve the method on a generic object which is error prone and should be handled with care. This is hazardous because it shows that the programmer "did not know" what kind of object was she expecting to handle and worked by assumption. Assumptions are great for finding a solution but are equally bad for implementing one.
If you thought of optimizing something in the way you did it, then, just FYI this actually creates a unique (redundant) name in the symbol table (in the compiled SWF file) which causes worse compression of the SWF.
If you are doing this as a matter of experiment, this is fine, but you should avoid such code in real life projects.
One more thing to be aware of: comparison to true constant is 100% useless. If such comparison makes any sense at all (i.e. findObject may evaluate to false any time), then if (findObject) { ... } is equivalent but shorter version of your code.
Last thing, hopefully, the anonymous function is missing return type declaration. It won't really change much in your example, except that you will get compiler warning. Omitting type declaration is, in general, a bad style.
EDIT
public function addEventListener(type:String, listener:Function ...):void
{
this._listeners[type].push(listener);
}
public function dispatchEvent(event:Event):void
{
for each (var listener:Function in this._listeners[event.type])
listener(event);
}
public function removeEventListener(type:String, listener:Function, ...):void
{
delete this._listeners[type][listener];
}
Suppose you actually want to implement IEventDispatcher (instead of using another EventDispatcher - you may have your reasons to do so, one such reason is that native EventDispatcher generates insane amounts of short-lived objects - events, and you may want to reduce that.) But there is no way you can replicate event.target or event.currentTurget in your code because you can't access the object owning the method, so, you would leave that out.
Another example:
public class SomeEvent extends Event
{
private var _target:NotEventDispatcher;
public function SomeEvent(type:String, someTarget:NotEventDispatcher)
{
super(type);
this._target = someTarget;
}
public override function get target():Object
{
return this._target;
}
}
This is something that I actually saw in real world, this was used in either Mate or similar framework to sort of "anonymously" connect all event dispatchers to a single static instance of some "mothership event dispatcher".
I don't necessarily justify this approach, but, technically, nothing stops you from doing either one of these. What I was saying in my post above is that in certain situations the language promises you things, like, if you did:
var dispatcher:IEventDispatcher;
try
{
dispatcher = IEventDispatcher(event.currentTarget);
// now you can be sure this object has removeEventListener
dispatcher.removeEventListener(event.type, arguments.callee);
}
catch (error:Error)
{
// but what are you going to do here?
}
But the most common case would be you subscribing to a bubbling event, in which case, you don't know whether you want to unsubscribe from event.target or event.currentTtarget - because you don't know which one is that you are listening to.
I agree with wvxvw.
Another way to approach your problem is to have a variable to control the "state" of your ENTER_FRAME event:
private var _state:String;
private function init(e:Event):void {
addEventListener(Event.ENTER_FRAME, loop, false, 0, true);
}
private function loop(e:Event):void {
switch(_state) {
case "play":
// do play stuff
// when you want to pause
// goToPause();
break;
}
}
// you can call the method below from a button or whatever you want
private function goToPause():void {
_state = "pause";
// do some stuff here
// when you are done, switch "_state" back to "play"
}
In this example, you keep listening for ENTER_FRAME, but it only does things when the _state variable is set to "play". You can also remove the event listener in the goToPause method:
private function goToPause():void {
_state = "pause";
removeEventListener(Event.ENTER_FRAME, loop);
}
However, the nice thing about using the "_state" to switch things is that you don't end up having a mess of addEventListeners and removeEventListeners (which is what can happen depending on how complicated your loop gets) that you have to keep track of.
You should not use anonymous function call if you would like to remove listener some time later.
public function main():void
{
//...
//some method, where you add event listener
//...
//adding enterFrame event listener
this.addEventListener(Event.ENTER_FRAME,enterFrameHandler);
//...
}
private function enterFrameHandler(e:Event)
{
if(findObject) // " == true" is not really necessary here.
{
// removing enterFrame listener:
this.removeEventlistener(Event.ENTER_FRAME,enterFrameHandler);
}
}
Just for a completeness with the other techniques mentioned here, the function you are creating is a unbound closure, so you can also leverage that concept to reference both your function and dispatcher.
var callback:Function;
var dispacher:IEventDispatcher = this;
addEventListener(Event.ENTER_FRAME, callback = function(e:Event){
if(findObject == true){
dispacher.removeEventListener(Event.ENTER_FRAME, callback);
}
});
Normal closed-over variable rules apply.

Clearing eventListeners on a FileReference object

I have a strange issue! I am trying to remove an event listener on a FileReference object by calling a function, but it seems not to be removed, and I do not understand why.
Here is the code:
private function clearFileUploadListeners(file:FileReference, index:String):void {
var dispatchEvent:Function = function(event:Event):void {
dispatch(event.type, event, index);
};
file.removeEventListener(Event.COMPLETE, dispatchEvent);
var bool:Boolean = file.hasEventListener(Event.COMPLETE);
if (bool)
trace("ERROR");
}
When I run this code, the trace actually happens. I don't understand why this boolean returns true, when I just tried to remove the eventListener just above! I guess I am probably doing something really stupid because it seems like a strange error.
I hope someone can please help me on this issue.
EDIT:
I believe it has to do with the fact that the dispatchEvent function is defined inside another function when I add the listener:
private function upload(file:FileReference, index:String):void {
var dispatchEvent:Function = function(event:Event):void {
dispatch(event.type, event, index);
};
file.addEventListener(Event.COMPLETE, dispatchEvent);
}
The problem is that I need to access this "index" variable from the listener, and I can't set it as a global variable as each file has it's own index and it's a burden if I have to extend each event class to keep track of the index (Event, ProgressEvent, ..). I hope someone can please help me on this.
EDIT2:
I actually found a temporary solution, I am not sure if it is the best! I put my removeListener method actually inside the upload method, but made it a variable. As AS3 allows dynamic object, I attached this method to one of my object, and so I just call the reference to the method when necessary. The event is actually removed. Is this a good solution please?
Thank you very much,
Rudy
You're right, it has to do with the fact that you're defining a function inside another function, then using it to handle events.
Each time the function upload is called, it creates a new closure, and assigns a reference to it to the dispatchEvent variable, which is then passed to the addEventListener class. So each time upload is called, it is using a new, different closure in the call to addEventListener. Similarly, in the clearFileUploadListeners function, a new closure is being created on each call (which happens to have the same code each time, but isn't the same function object). The call to removeEventListener does nothing if the given callback has not been added as an event listener for the given event, which is the case here.
To solve your problem, you need to store a reference to the closure that you pass to the addEventListener function. This way, you can get a reference to the same closure that was added when you need to remove it later in clearFileUploadListeners.
You can try something along the lines of the following code (untested):
import flash.utils.Dictionary;
var callbackRegistry:* = new Dictionary();
private function upload(file:FileReference, index:String):void {
var dispatchEvent:Function = generateFileUploadCompleteCallback();
callbackRegistry[file] = dispatchEvent;
file.addEventListener(Event.COMPLETE, dispatchEvent);
}
private function clearFileUploadListeners(file:FileReference, index:String):void {
var dispatchEvent:Function = callbackRegistry[file];
callbackRegistry[file] = null;
file.removeEventListener(Event.COMPLETE, dispatchEvent);
var bool:Boolean = file.hasEventListener(Event.COMPLETE);
if (bool)
trace("ERROR");
else
trace("YAY, ALL OK!");
}
private function generateFileUploadCompleteCallback(index:String):Function {
return function(event:Event):void {
dispatch(event.type, event, index);
};
}
Two other things to note on this subject.
If you must utilize a native Event directly then you should pretty much always make sure and use these last three optional params :
myObject.addEventListener( Event.COMPLETE, myFunction, false, 0, true );
Check Grant Skinner's post on the subject here :
http://gskinner.com/blog/archives/2006/07/as3_weakly_refe.html
And the very best practice of all is to ALWAYS (seriously always) use Robert Penner's Signals (instead of custom events) and his NativeSignals (to wrap needed native Flash events).
Five times faster than Flash's native events.
Always safe with weak references.
Any number of typed payload(s) in each Signal.
Get the SWC here :
https://github.com/robertpenner/as3-signals
Signals were designed to solve the very problem you are having.
Imagine instead of creating an array and managing that to remove all listeners if you could just call :
signalBtnClicked.removeAll();
or
signalBtnClicked.addOnce( function( e : MouseEvent ) : void { /* do stuff */ } );
Knowing that the closure you just created will immediately be dereferenced once it is called and happily go night night when the GC makes its rounds.