我将如何为数组对象添加addEventListener。
我试图避免每隔x毫秒运行一个计时器来检查数组对象中的新元素,而不是在检测到新元素处理它们并将其删除时尝试触发事件。
阵列可以吗?也许ArrayCollections?要么就好了。
P.S.>这是 Flash 问题不 javascript
答案 0 :(得分:1)
为什么不创建自己的数组类来扩展Array并实现IEventDispatcher,重写push()函数并让它在调用函数时调度一个事件?
类似于:
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);
}
}
}
答案 1 :(得分:0)
如何扩展Array.prototype.push
方法?从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);
};
})();
在内部函数体中抛出您想要的任何代码。
答案 2 :(得分:0)
发现
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));
}
与meder的帮助
答案 3 :(得分:0)
private var myArray:Array;
private function addToArray(element:Object):void
{
myArray.push(element);
dispatch( new Event("Element added));
}
或在静态函数中,如果你想从另一个类中调用它
public static function addToArray( array:Array , element:Object , dispatcher:EventDispatcher):Array
{
array.push(element);
dispatcher.dispatch( new Event('Added Element') );
return array;
}
实施实际上取决于您的环境。