liriliri / licia

Useful utility collection with zero dependencies
https://licia.liriliri.io
MIT License
2.29k stars 158 forks source link

fix Emitter cannot be canceled correctly #7

Closed Easy-Martin closed 6 years ago

Easy-Martin commented 6 years ago
const Emitter = require('licia/Emitter')
var event = new Emitter()
function test() {
    this.name = 'aaa'

    event.on('aaa', () => {
        this.callback2()
    })
    event.on('aaa',  () => {
        this.callback2()
    })
    event.on('aaa', () => {
        this.callback()
    })
    event.on('aaa',  () => {
        this.callback()
    })

    event.off('aaa',  () => {
        this.callback2()
    })
    event.off('aaa',  () => {
        this.callback2()
    })

    event.emit('aaa')
}
test.prototype.callback = function() {
    console.log(this.name)
}
test.prototype.callback2 = function() {
    console.log(this.name + 222222222)
}

new test()
// result
// aaa222222222
// aaa222222222

//Correct result
// aaa
// aaa
surunzi commented 6 years ago

It is expected to use the same handler reference when unbinding events.

let callback = () => { this.callback2() }
event.on('aaa', callback)
event.off('aaa', callback)
Easy-Martin commented 6 years ago

ok,but there are problems when linstener is undefined this._events[event].splice(-1,1 )

shouldn't it be like this?

var index = this._events[event].indexOf(listener)
index !== -1 && this._events[event].splice(index, 1);