Simple component invalidation in AS3

When we develop components, it quickly becomes necessary not to update the display every time we change a parameter.

For example, this code calls three times my draw method :

1
2
3
myComps.width = 100;
myComps.height = 100;
myComps.color = 0xFF0000;

Mmmm ? Stupid ?

The solution is to wait for the next enterFrame event to update the display.
The UIComponent that is the base of Flash components offers all the methods to do this, but the last thing I want is to use them.

Here’s how to set up a simple invalidation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package
{
	import flash.display.Sprite;
	import flash.events.Event;
 
	public class InvalidateSprite extends Sprite 
	{
		private var _width:Number = 150;
		private var _height:Number = 100;
		private var _color:Number = 0xCCCCCC;
 
		public function InvalidateSprite(){
			_invalidate();
		}
 
		public override function set width(value:Number):void {
			_width = value;
			_invalidate();
		}
 
		public override function set height(value:Number):void {
			_height = value;
			_invalidate();
		}
 
		public function set color(value:Number):void {
			_color = value;
			_invalidate();
		}
 
		private function _draw():void {
			graphics.clear();
			graphics.beginFill(_color, 1);
			graphics.drawRect(0, 0, _width, _height);
		}
 
		private function _invalidate():void {
			if(!hasEventListener(Event.ENTER_FRAME))
				addEventListener(Event.ENTER_FRAME, _invalidateCallback);
		}
 
		private function _invalidateCallback(e:Event):void {
			removeEventListener(Event.ENTER_FRAME, _invalidateCallback);
			_draw();
		}
	}
}

2 thoughts on “Simple component invalidation in AS3

  1. Nice, attaching an ENTER_FRAME event to any sprite can be expensive, I would instead attach it to the stage:

    private function _invalidate():void {
    if(!stage.hasEventListener(Event.ENTER_FRAME))
    stage.addEventListener(Event.ENTER_FRAME, _invalidateCallback);
    }

    private function _invalidateCallback(e:Event):void {
    stage.removeEventListener(Event.ENTER_FRAME, _invalidateCallback);
    _draw();
    }

Leave a Reply

Your email address will not be published. Required fields are marked *