简体   繁体   中英

node.js custom events: Cannot call method 'emit' of undefined

I'm learning node, its events API and trying to make a simple example.

So here's my code:

var fs = require('fs');
var util = require('util');
var events = require('events');
var FileLoader = function () {
    events.EventEmitter.call(this);
    this.load = function (url) {
        fs.readFile(url, function (err, data) {
            if (err) {
                throw err;
             } else {
                this.emit('loaded', data.toString());
            }
        });
    };
};
util.inherits(FileLoader, events.EventEmitter);
module.exports = FileLoader;

And I want to load() a text file and when it is loaded, catch it with .on('loaded',function(){...}) , but this is undefined, so program crashes.

I'm definitely missing something, how to make it work?

This is not an issue with Node, it is an issue with JavaScript. The this in this.emit is not a FileLoader instance.

I recommend you read up on the behavior of this in JavaScript. The MDN docs for this may be helpful for you.

In this case, you need to bind the this inside your readFile callback so that the inner this is the outer this by adding .bind(this) to your callback.

this.load = function (url) {
    fs.readFile(url, function (err, data) {
        if (err) {
            throw err;
         } else {
            this.emit('loaded', data.toString());
        }
    }.bind(this));
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM