但是,使用 jQuery 发出事件需要有一个 DOM 对象,而且不能从任意对象发出事件。这就是事件发射器变得有用的地方。下面是一些演示自定义事件的伪代码(与上面完全相同的模式) :
// Create custom object which "inherits" from emitter. Keyword "extend" is just a pseudo-code.
var myCustomObject = {};
extend(myCustomObject , EventEmitter);
// Subscribe to event.
myCustomObject.on("somethingHappened", function() {
alert("something happened!");
});
// Emit event.
myCustomObject.emit("somethingHappened");
var EventEmitter = require('events').EventEmitter;
var concert = new EventEmitter;
var singer = 'Coldplay';
concert.on('start', function (singer) {
console.log(`OMG ${singer}!`);
});
concert.on('finish', function () {
console.log(`It was the best concert in my life...`);
});
concert.emit('start', singer);
concert.emit('finish');