Skip to content

监听事件

关键方法

on ( )

on(type: string | string[], listener: IEventListener, options?: IEventListenerOptions | boolean)

侦听事件, options 为 boolean 时表示是否为 捕获类型

once ( )

once(type: string | string[], listener: IEventListener, capture?: boolean)

只侦听一次事件,capture 表示是否为 捕获类型

新方法

on_()

on_(type: string | string[], listener: IEventListener, bind?: IObject, options?: IEventListenerOptions | boolean): IEventListenerId

侦听事件,支持传入 bind 作为 listener 的 this 对象,并返回事件 id,与 off_() 配套使用。

ts
import { IEventListenerId } from '@leafer/interface'
import { UI, PointerEvent } from 'leafer-ui'

export class Simple extends UI {

    events: IEventListenerId[]

    listen() { 
        this.events = [
            this.on_(PointerEvent.ENTER, this.enter, this),
            this.on_(PointerEvent.LEAVE, this.leave, this)
        ]
    }

    cancel(): void {
        this.off_(this.events)
    }

    enter() { }
    leave() { }

}

示例

监听单个事件

ts
import { Leafer, Rect, PointerEvent } from 'leafer-ui'

const leafer = new Leafer({ view: window })

const rect = new Rect({ x: 100, y: 100, fill: '#32cd79', draggable: true })

leafer.add(rect)

function onEnter(e: PointerEvent) {
    (e.current as Rect).fill = '#42dd89'
}

rect.on(PointerEvent.ENTER, onEnter)  

监听多个事件

数组形式:

ts
import { Leafer, Rect, PointerEvent } from 'leafer-ui'

const leafer = new Leafer({ view: window })

const rect = new Rect({ x: 100, y: 100, fill: '#32cd79', draggable: true })

leafer.add(rect)

function onEnter(e: PointerEvent) {
    (e.current as Rect).fill = '#42dd89'
}

function onLeave(e: PointerEvent) {
    (e.current as Rect).fill = '#32cd79'
}

rect.on([PointerEvent.ENTER, PointerEvent.LEAVE], 
    function (e: PointerEvent) {
        if (e.type === PointerEvent.ENTER) {
            onEnter(e)
        } else {
            onLeave(e)
        }
    }
)

字符串形式:

ts
import { Leafer, Rect, PointerEvent } from 'leafer-ui'

const leafer = new Leafer({ view: window })

const rect = new Rect({ x: 100, y: 100, fill: '#32cd79', draggable: true })

leafer.add(rect)

function onEnter(e: PointerEvent) {
    (e.current as Rect).fill = '#42dd89'
}

function onLeave(e: PointerEvent) {
    (e.current as Rect).fill = '#32cd79'
}

rect.on('pointer.enter pointer.leave', 
    function (e: PointerEvent) {
        if (e.type === 'pointer.enter') {
            onEnter(e)
        } else {
            onLeave(e)
        }
    }
)

只监听一次事件

ts
import { Leafer, Rect, PointerEvent } from 'leafer-ui'

const leafer = new Leafer({ view: window })

const rect = new Rect({ x: 100, y: 100, fill: '#32cd79', draggable: true })

leafer.add(rect)

function onEnter(e: PointerEvent) {
    (e.current as Rect).fill = '#42dd89'
}

function onLeave(e: PointerEvent) {
    (e.current as Rect).fill = '#32cd79'
}

rect.once('pointer.enter', onEnter) 
rect.once('pointer.leave', onLeave)

Released under the MIT License.