How would I go about as to addEventListener for a array object.
I'm trying to avoid running a timer every x milliseconds to check for new elements in array object, rather trying to make a event fire when new elements are detected to process them and remove them.
Is it possible with Arrays? maybe ArrayCollections? either is fine.
P.S.> This is开发者_C百科 Flash question not javascript
Why not create your own array class that extends Array and implements the IEventDispatcher, override the push() function and make it dispatch an event when the function is called?
So something like:
package
{
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
public class MyArray extends Array implements IEventDispatcher
{
public static var ARRAY_PUSHED:String = "MYARRAY_ARRAY_PUSHED";
private var dispatcher:EventDispatcher;
public function MyArray(...parameters)
{
super(parameters);
dispatcher = new EventDispatcher(this);
}
override public function push(...parameters):uint
{
dispatchEvent(ARRAY_PUSHED);
super.push(parameters);
}
public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int=0, useWeakReference:Boolean=false):void
{
dispatcher.addEventListener(type, listener, useCapture, priority);
}
public function dispatchEvent(e:Event):Boolean
{
return dispatcher.dispatchEvent(e);
}
public function hasEventListener(type:String):Boolean
{
return dispatcher.hasEventListener(type);
}
public function removeEventListener(type:String, listener:Function, useCapture:Boolean=false):void
{
dispatcher.removeEventListener(type, listener, useCapture);
}
public function willTrigger(type:String):Boolean
{
return dispatcher.willTrigger(type);
}
}
}
How about extending the Array.prototype.push
method? Stolen from How to extend Array.prototype.push()?
Array.prototype.push=(function(){
var original = Array.prototype.push;
return function() {
//Do what you want here.
return original.apply(this,arguments);
};
})();
Throw any code that you want inside of the inner function body.
found
AS3 override function push(...args):uint
{
for (var i:* in args)
{
if (!(args[i] is dataType))
{
args.splice(i,1);
}
}
return (super.push.apply(this, args));
}
with meder's help
private var myArray:Array;
private function addToArray(element:Object):void
{
myArray.push(element);
dispatch( new Event("Element added));
}
or in a static function if you wanted to call this from another class
public static function addToArray( array:Array , element:Object , dispatcher:EventDispatcher):Array
{
array.push(element);
dispatcher.dispatch( new Event('Added Element') );
return array;
}
The implementation really depends on your environment.
精彩评论