自定义事件开发

更新时间: 2021-08-05 08:50:48

主要的功能开发得差不多了,这个插件长得有点丑的问题先不解决,先解决一下自定义事件的问题。在使用过程中,我们需要知道什么时候拖拽改了位置,什么时候改了大小,什么时候又销毁了实例。这个时候使用自定义事件就可以很好解决。

# 开发event类

先写一个event类,主要就是通过一个handlers变量记录。

class Event {
    constructor(){
        this.handlers = {}
    }
    on(type,handler){
        if(typeof this.handlers[type] === "undefined"){
            this.handlers[type] = []
        }
        this.handlers[type].push(handler)
    }
    emit(type,event){
        if(!event.target){
            event.target = this
        }
        if(this.handlers[type] instanceof Array){
            const handlers = this.handlers[type]
            handlers.forEach((handler)=>{
                handler(event)
            })
        }
    }
    off(type,handler){
        if(this.handlers[type] instanceof Array){
            const handlers = this.handlers[type]
            for(var i = 0,len = handlers.length; i < len; i++){
                if(handlers[i] === handler){
                    break;
                }
            }
            handlers.splice(i,1)
        }
    }
}

export default Event
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

然后让Accelerator类继承Event类:

class Accelerator extends Event{
    //....
}
1
2
3

然后在需要抛出事件的时候调用emit方法,例如抛出dragStart事件:

this.emit('dragStart',{target:this})
1

然后接收事件:

const ac = new Accelerator(domEl,{
    x:'0%',
    y:'0%',
    width:'10%',
    height:'10%'
})
ac.on('dragStart',function() {
    console.log('开始拖拽')
})
1
2
3
4
5
6
7
8
9