如何将范围传递给nodejs中的回调函数?

时间:2013-03-18 19:17:50

标签: javascript node.js

我正在使用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函数?

由于 克里斯

1 个答案:

答案 0 :(得分: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));