node中所有能触发的事件对象都是EventEmitter的实例化(new EventEmitter)。EventEmitter实例化对象的on()监听事件,允许将一个或者多个函数绑定到会被对象触发的命名事件上,事件名称通常是驼峰式的字符串。通过emit()绑定事件命名触发事件。
//实例化事件对象
const event = require('events');
const emitter = new event.EventEmitter();
//绑定事件
function eventDemo(args){
console.log("事件执行 参数"+args);
}
emitter.on('demo', eventDemo);
//触发事件
emitter.emit('demo','234');
事件属性:
1、最大监听事件数(defaultMaxListeners)
const event = require('events');
console.log('最大事件监听数 '+event.defaultMaxListeners);
2、事件
newListener (内置事件,自动触发监听器)
const event = require('events');
const emitter = new event.EventEmitter();
emitter.on('newListener', function(event, listener){
console.log("添加了新的监听事件!"+event);
});
emitter.on('a', function(){
console.log('a 事件!');
});
emitter.on('a', function(){
console.log('b 事件!');
});
emitter.emit('a');
removeListener(移除事件)
removeAllListeners (移除全部监听事件)
const event = require('events');
const emitter = new event.EventEmitter();
emitter.on('removeListener', function(event, listener){
console.log(event+'事件移除!!');
});
emitter.on('a', function(){
console.log('a 事件!');
});
emitter.on('b', function(){
console.log('b 事件!!');
});
emitter.removeAllListeners();
属性:
on (添加事件监听器)
addListener on()方法的别名
once() 事件只能触发一次
const event = require('events');
const emitter = new event.EventEmitter();
emitter.once('a', function(){
console.log('a 事件!!!');
});
emitter.emit('a');
emitter.emit('a');
prependListener () 优先加载
prependOnceListener 优先加载
const event = require('events');
const emitter = new event.EventEmitter();
emitter.on('a', function(){
console.log('a 事件!!');
});
emitter.on('a', function(){
console.log('b 事件!');
});
emitter.prependListener('a', function(){
console.log('c 事件!');
});
emitter.emit('a');
事件原型链扩展:
//定义监听事件1
var listener1 = function listener1(arg) {
console.log("listener1:" + arg);
}
//原型链实现继承
var EventEmitter = require('events').EventEmitter;
function Client() {}
Client.prototype.a = function() {
console.log("a");
}
Client.prototype.__proto__ = EventEmitter.prototype;
var client = new Client();
client.a(); //a
client.on('extend', listener1)
client.emit('extend', "Hello World"); // listener1:Hello World
事件es6扩展实例:
//loginEvent.js
const EventEmitter = require('events');
class UserBean extends EventEmitter{
constructor(username, password){
super();
this.username = username;
this.password = password;
}
login(){
if(this.username=='aa' && this.password=='123'){
this.emit('success');
}else{
this.emit('error');
}
}
}
module.exports = UserBean;
//login.js
const User = require('./loginEvent');
const user = new User('a','123');
user.on('success', function(){
console.log('登录成功!');
});
user.on('error', function(){
console.log('登录失败!');
});
user.login(); //登录失败
以上就是个人关于事件的了解
参考:事件 事件