gpt4 book ai didi

javascript - 绑定(bind)从成员函数发出的事件

转载 作者:太空宇宙 更新时间:2023-11-04 01:05:19 25 4
gpt4 key购买 nike

js 和 EventEmitters。我下面有以下代码。我想知道如何在调用“getTime()”函数时绑定(bind)“时间”事件。像这样的事情:

timer.getTime.on("time", function() {
console.log(new Date());
});

--代码--

var EventEmitter = require('events').EventEmitter;

function Clock() {
var self = this;
this.getTime = function() {
console.log("In getTime()");
setInterval(function() {
self.emit('time');
console.log("Event Emitted!!");
}, 1000);
};
}

Clock.prototype = EventEmitter.prototype;
Clock.prototype.constructor = Clock;
Clock.uber = EventEmitter.prototype;

var timer = new Clock();

timer.getTime.on("time", function() {
console.log(new Date());
});

最佳答案

为什么不直接这样:

timer.on("time", function() {
console.log(new Date());
});

timer.getTime();

虽然您是从方法内发出事件,但方法和事件之间没有其他关系。您订阅 Clock 对象上的事件,并在时钟对象上发出事件。

另外,这很糟糕,永远不要这样做:

Clock.prototype = EventEmitter.prototype;

你想这样做:

Clock.prototype = Object.create(EventEmitter.prototype);

关于javascript - 绑定(bind)从成员函数发出的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23631804/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com