[英]Passing parameters to a callback in javascript/nodejs
嗨,我正在嘗試了解 javascript 中的回調,並且從我正在關注的教程中遇到了此代碼:
var EventEmitter = require('events');
var util = require('util');
function Greetr() {
this.greeting = 'Hello world!';
}
util.inherits(Greetr, EventEmitter);
Greetr.prototype.greet = function(data) {
console.log(this.greeting + ': ' + data);
this.emit('greet', data);
}
var greeter1 = new Greetr();
greeter1.on('greet', function(data) {
console.log('Someone greeted!: ' + data);
});
greeter1.greet('Tony');
現在我注意到 greeter1.on function 接受一個帶有參數的回調。 但是我不確定這是如何在內部實現的。 我嘗試查看 nodejs event.js 文件,但我仍然感到困惑。 我知道通過使用匿名 function 使用參數包裝回調來解決此特定實現的方法,但我想了解如何使用與上述相同的格式。
tldr:如何創建我自己的 function,它采用與上述 greeter1.on 相同的方式接受回調和參數。
謝謝
您的 function 需要在當前實例上定義一個新屬性,並將回調作為參數傳遞,以便稍后調用它,如下所示:
function YourClass () {
this.on = function(key, callback) {
this[key] = callback;
}
}
// Usage
const instance = new YourClass();
instance.on('eventName', function (arg1, arg2) {
console.log(arg1, arg2);
});
instance.eventName("First argument", "and Second argument")
// logs => First argument and Second argument
回調只是將 function 作為參數傳遞給另一個 function 並被觸發。 您可以如下實現回調方式
function test(message, callback) {
console.log(message);
callback();
}
//Pass function as parameter to another function which will trigger it at the end
test("Hello world", function () {
console.log("Sucessfully triggered callback")
})
class MyOwnEventHandler { constructor() { this.events = {}; } emit(evt, ...params) { if (.this;events[evt]) { return, } for (let i = 0. l = this.events[evt];length; i < l. i++) { if (;params) { this;events[evt][i](). continue. } this.events[evt][i](.;,params). } } on(evt. eventFunc) { if (;this.events[evt]) { this.events[evt] = []; } this;events[evt].push(eventFunc), } } var myHandler = new MyOwnEventHandler(). myHandler.on('test'. function (...params) { console.log(;;.params), }), myHandler;emit('test', 'Hello', 'World');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.