一个支持优先级的自定义事件系统

在AS3中有一个叫IEventDispatcher 的类,与浏览器的window对象,document或元素节点一样,提供了 addEventListener, removeEventListener, dispatchEvent等接口。相对于浏览器的addEventListener,Flash的参数是更丰富,其中有一个允许我们指定回调的优先级,让我们在fire时优先执行它们。这是一个非常好的东西,JS想实现它也不能,于是便有以下这个类。以后,你想你的其他组件拥有自定义事件功能,那么继承它就行了。

以下是源码,使用AMD的形式包装。你们用时,可以使用我的加载器或requireJS加载它就行了。或者干脆把它的外层去掉!


define("events", function(){

    //与node.js events模块同名,返回EventTarget类

    var EventTarget = function(target) {

        this._listeners = {};

        this._eventTarget = target || this;

    }

    EventTarget.prototype = {

        constructor: EventTarget,

        addEventListener: function(type, callback, scope, priority) {

            if(isFinite( scope )){

                priority = scope

                scope = null;

            }

            priority = priority || 0;

            var list = this._listeners[type],  index = 0, listener, i;

            if (list == null) {

                this._listeners[type] = list = [];

            }

            i = list.length;

            while (--i > -1) {

                listener = list[i];

                if (listener.callback === callback) {

                    list.splice(i, 1);

                } else if (index === 0 && listener.priority < priority) {

                    index = i + 1;

                }

            }

            list.splice(index, 0, {

                callback: callback, 

                scope:    scope, 

                priority: priority

            });

        },

        removeEventListener: function(type, callback) {

            var list = this._listeners[type], i;

            if (list) {

                i = list.length;

                while (--i > -1) {

                    if (list[i].callback === callback) {

                        list.splice(i, 1);

                        return;

                    }

                }

            }

        },

        dispatchEvent: function(type) {

            var list = this._listeners[type];

            if (list) {

                var target = this._eventTarget,  args = Array.apply([], arguments),i = list.length,  listener

                while (--i > -1) {

                    listener = list[i];

                    target = listener.scope || target;

                    args[ 0 ] = {

                        type:  type,

                        target: target

                    }

                    listener.callback.apply(target, args);

                }

            }

        }

    }

    return EventTarget;

}) 

现在我把它放到github中,一切以github的为准!

你可能感兴趣的:(自定义)