0

我正在使用 nodejs 和 xml2js 模块。我正在读取一个 XML 文件并尝试在将 xml 转换为 json 对象后发出一个事件。我的代码如下所示:

var fs = require('fs'),
util = require('util'),
events = require('events'),
xml2js = require('xml2js');

var CIRCUITMODELSFILENAME = "ControlCircuitModels.xml";
var CIRCUITPARTMODELSFILENAME = "ControlCircuitParts.xml";
var circuitModels, circuitPartModels;


function ModelController() {
    if (false === (this instanceof ModelController)) {
        return new ModelController();
    }
    events.EventEmitter.call(this);
};


util.inherits(ModelController, events.EventEmitter);


ModelController.prototype.load = function (baseDir) {

    var parser = new xml2js.Parser({
        normalize: true,
        trim: true,
        explicitArray: false
    });

    fs.readFile(baseDir + "/" + CIRCUITMODELSFILENAME, function (err, data) {
        parser.parseString(data, function (err, result) {
            circuitModels = result;
            console.log('circuit models loaded');
            parser.reset();
            fs.readFile(baseDir + "/" + CIRCUITPARTMODELSFILENAME, function (err, data) {
            parser.parseString(data, function (err, result) {
                circuitPartModels = result;
                console.log('circuit part models loaded');
                moduleReady = true;
                this.emit("modelsloaded", null);
                });
            });
        });
    });
};

// public interface
exports.ModelController = ModelController;

问题是发出事件时的范围丢失了。

this.emit("modelsloaded", null);

这没有从 EventEmitter 继承发射。

如何将范围传递给 parser.parseString 函数?

谢谢克里斯

4

1 回答 1

0

不确定这是否是最好的解决方案,除此之外它有效(看起来并不直接):

fs.readFile(baseDir + "/" + CIRCUITMODELSFILENAME, function (err, data) {
    parser.parseString(data, function (err,result) {
        circuitModels = result;
        parser.reset();
        fs.readFile(baseDir + "/" + CIRCUITPARTMODELSFILENAME, function (err, data) {
            circuitPartModels = result;
            console.log('circuit models loaded');
            parser.parseString(data, function (err, result) {
                console.log('circuit part models loaded');
                this.emit("modelsloaded", null);
                moduleReady = true;
                circuitPartModels = result;
            }.bind(this));
        }.bind(this));
    }.bind(this));
}.bind(this));
于 2013-03-18T20:14:19.443 回答