1.0.0 • Published 2 years ago

esdrop v1.0.0

Weekly downloads
-
License
ISC
Repository
-
Last release
2 years ago

eSdrop

Eave Sdrop

  • 优点: 小而美

虽然eSdrop是基于浏览器应用的,但为了能保持最好的效果,请在IE9+上使用它

目录

安装

将esdrop添加为项目的依赖

$ npm install --save esdrop

在你的项目中引用它:

// ES Modules
import esdrop from 'esdrop'

// CommonJS 
const esdrop = require('esdrop')

const eventBus = esdrop()

API

eventBus.on(eventName, callback)

监听全局的自定义事件,事件由 emit 触发,回调函数会接收事件触发函数的传入参数。 | 属性 | 类型 | 描述 | | ---- | ---- | ---- | | eventName | String | 事件名 | | callback | Function | 回调函数 |

代码示例

eventBus.on('test', e=>{
	console.log('监听到test事件,携带的参数为:', e);
})

eventBus.once(eventName, callback)

监听全局的自定义事件,事件由 emit 触发,但仅触发一次,在第一次触发之后移除该监听器。 | 属性 | 类型 | 描述 | | ---- | ---- | ---- | | eventName | String | 事件名 | | callback | Function | 回调函数 |

代码示例

eventBus.once('test', e=>{
	console.log('监听到test事件,携带的参数为:', e);
})

eventBus.emit(eventName, ...params)

触发全局的自定义事件,附加参数都会传给监听器回调函数。 | 属性 | 类型 | 描述 | | ---- | ---- | ---- | | eventName | String | 事件名 | | params | Any<Any[]> | 触发事件携带的附加参数 |

代码示例

eventBus.emit('test', '触发test事件并携带参数')

eventBus.off(eventName, callback)

移除全局自定义事件监听器。 | 属性 | 类型 | 描述 | | ---- | ---- | ---- | | eventName | String | 事件名 | | callback | Function | 回调函数 |

Tips

  • 如果eventBus.off没有传入参数,则移除所有事件监听器;
  • 如果只提供了事件名(eventName),则移除该事件名对应的所有监听器;
  • 如果同时提供了事件与回调,则只移除这个事件回调的监听器;
  • 提供的回调必须跟eventBus.on的回调为同一个才能移除这个回调的监听器;

代码示例

eventBus.on('test', test)
eventBus.off('test', test)
function test(){
	console.log('test事件触发了')
}

示例

import esdrop from 'esdrop'
const eventBus = esdrop()

// 1. 监听click事件触发
eventBus.on('click',e=>{
	console.log(e) // => '123'
})
div.onclick = function(){
	eventBus.emit('click', '123')
}

// 2. 监听click事件触发 完成后销毁监听
eventBus.once('click',e=>{
	console.log(e) // => '123'
})
div.onclick = function(){
	eventBus.emit('click', '123')
}

// 3. 取消click事件对应的test1回调
eventBus.on('click', test1)
eventBus.on('click', test2)

div.onclick = function(){
	eventBus.off('click', test1) // 仅取消 click事件里 test1的回调
	// eventBus.off('click') // 取消 click事件里 所有的回调
	// eventBus.off() // 仅所有的事件回调
	eventBus.emit('click', '321')
}

function test1(e){
	console.log(e) // 不会被触发,已被取消
}
function test2(e){
	console.log(e) // => '321'
}