DomingoSL
DomingoSL

Reputation: 15494

dispatchEvent from class to timeline

I know is not the best practice, but for this example i must continue with this scheme:

In my timeline i have this:

 addEventListener(KeyboardEvent.KEY_DOWN,handler);
function handler(event:KeyboardEvent){
   if(event.charCode == 13){
       trace('enter pressed');
   }
}

Just a very simple enter key listener. In a class sometimes an action is triggered and I need to simulate the enter key press from the class in the timeline:

case 'enter':
{
  trace('it works!');
  dispatchEvent(new KeyBoardEvent(KeyBoardEvent.ENTER));    
  return;
}

I know the case is triggered bucause i see the trace msg. But my handler function is not triggered. How can i solve this? In a few words, the only thing i need is to execute a function located in my timeline from an external class.

Upvotes: 0

Views: 701

Answers (2)

Amy Blankenship
Amy Blankenship

Reputation: 6961

Your problem is that you have a design flaw, not a code problem. You have "something" you want to have happen. Sometimes, you want it to happen because a key was pressed. Sometimes you want it to happen for some other reason.

When you look at it like this, it's now obvious that this is business logic, not in the realm of things that a View should be deciding. It is possible that the "something" is also not the responsibility of the View. You haven't said what it is, so there is no way to really know based on your question. Let's assume for the sake of argument that it is properly a View responsibillity.

Now, if you add a something() method to your View, then the party that is responsible in your question for generating a "fake" event can now call that method in response to whatever conditions you need it to. That party may also be in a role where it makes sense for it to be watching the stage for KEY_DOWN events, or it may not. By simplifying the API on your View, you make it possible for a parent View or separate Controller to handle this without affecting the logic in the View.

Another possible solution is a bit more advanced, and that is to create a new EventDispatcher that you provide to all the instances you want to be able to communicate. In this model, your View would listen for a DO_SOMETHING event on that EventDispatcher, then do something. This DO_SOMETHING would be dispatched as a result of the keyboard event, the other condition you want to handle, or any future requirement that would result in "something."

Upvotes: 0

jaku
jaku

Reputation: 36

you need to dispatchEvent to object where listener is added.
In excample if your:
addEventListener(KeyboardEvent.KEY_DOWN,handler);
is in main timeline you should write
MovieClip(root).dispatchEvent(new KeyBoardEvent(KeyBoardEvent.KEY_DOWN));
when you dispatch from another MovieClip, or object added to root.

Upvotes: 1

Related Questions