THREE.JS源码:EventDispatcher

事件调度,是一个事件的容器,Object3D继承自该类,说明该类是three.js的实体基类,作用是隔离事件触发与事件处理的过程,降低实体之间的耦合度。

//定义事件调度类

function EventDispatcher() {}

//定义该类的原型

Object.assign( EventDispatcher.prototype, {
        //添加事件监听,可针对同一个事件添加多个监听

        addEventListener: function ( type, listener ) {
      
        // 如果监听集合为未定义就创建
        if ( this._listeners === undefined ) this._listeners = {};

        //获取监听对象
        const listeners = this._listeners;

        //如果type类型的监听不存在就创建,该类型的数组
        if ( listeners[ type ] === undefined ) {
            //定义监听数组
            listeners[ type ] = [];

        }
        //如果监听集合中不包含该类型的处理过程,则加入处理
        if ( listeners[ type ].indexOf( listener ) === - 1 ) {
            listeners[ type ].push( listener );

        }

    },

    //监测是否包含该类型的监听
    hasEventListener: function ( type, listener ) {
        //没有监听集合
        if ( this._listeners === undefined ) return false;
        //含有监听集合
        const listeners = this._listeners;
        //监听存在检查
        return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;

    },

    //移除监听
    removeEventListener: function ( type, listener ) {
        if ( this._listeners === undefined ) return;

        const listeners = this._listeners;
        const listenerArray = listeners[ type ];

        if ( listenerArray !== undefined ) {
            const index = listenerArray.indexOf( listener );

            if ( index !== - 1 ) {
                //移除监听
                listenerArray.splice( index, 1 );

            }

        }

    },

    //调度事件
    dispatchEvent: function ( event ) {
        if ( this._listeners === undefined ) return;

        const listeners = this._listeners;
        const listenerArray = listeners[ event.type ];

        if ( listenerArray !== undefined ) {
            event.target = this;

            // Make a copy, in case listeners are removed while iterating.
            // 拷贝一份,防止监听在处理时被删除
            const array = listenerArray.slice( 0 );

            for ( let i = 0, l = array.length; i < l; i ++ ) {
                //调用处理过程,其中处理过程中的this是EventDispatcher类,可能是针对dom事件才这样处理的,自定义类应该不会起作用
                array[ i ].call( this, event );

            }

        }

    }

} );


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部