0

Hi I'm trying to understand callbacks in javascript and have come across this code here from a tutorial that I'm following:

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');

Now I notice that the greeter1.on function takes a callback with a parameter. However I'm not sure how this is implemented internally. I tried looking through the nodejs event.js file but I'm still confused. I am aware that there are ways around this specific implementation by using an anonymous function wrapping the callback with parameters but I want to understand how to use the same format as above.

tldr: How can I create my own function that takes a callback and a parameter in the same fashion as greeter1.on above.

Thank you

3 Answers 3

2

Your function needs to define a new property on the current instance with the callback passed as an argument, so it can be called later, like so:

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

Sign up to request clarification or add additional context in comments.

Comments

0

Callback is just passing a function as a parameter to another function and that being triggered. You can implement callback fashion as below

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")
})

Comments

0

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');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.