Stop event propagation

I was coding a small control. When it’s clicked, it unfolds itself and starts to respond to user input; when the user clicks anywhere after this, it folds back and stops responding to user input.

Basically there are two sources for the click event: the object itself and the Stage. Based on which state the object is in, it behaves differently. Here is what the mouse click handler looks like:

removeEventListener(MouseEvent.CLICK, handleClick);
stage.addEventListener(MouseEvent.CLICK, handleClick);
}else if(_state==UNFOLDED)
stage.removeEventListener(MouseEvent.CLICK, handleClick); addEventListener(MouseEvent.CLICK, handleClick);
_state = (_state == FOLDED)? UNFOLDED: FOLDED;

The control didn’t seem to change its state with just this code. The reason is that once one source is removed from the event listeners list, another one is added to the list. Since the click event continues to bubble through, and the two sources are executing the same code (as shown above), so the switch between states seems to ultimately cancel each other.


To make it work, just add one line on top of the code, like this:


This eventually makes the state transfer smooth.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: