我的助手文件夹中有两个文件,一个是EventHelper.jsUserEvent.js

helpers / EventHelper.js

function EventHelper() {
  this.onEventCreated = function(err, e) {...}
  this.isExisting = function(id) {...}
}
module.exports = new EventHelper();


helpers / UserEvent.js

var EventHelper1 = require('./EventHelper')
var EventHelper2 = require('./EventHelper.js')

function UserEvent() {
  this.fireEvent = function(req, res) {
    var EventHelper3 = require('./EventHelper');
    ...
    EventHelper1.onEventCreated(err, e);
    EventHelper2.onEventCreated(err, e);
    EventHepler3.onEventCreated(err, e);
  }
};
module.exports = new UserEvent();


controllers / EventController.js

 var EventHelper = require('../helpers/EventHelper')
    var UserEvent = require('../helpers/UserEvent');

    var EventController = {
      fireEvent: function(req, res) {
        if(EventHelper.isExisting(req.params.id)) UserEvent.fireEvent(req, res)
        ...
      }
    }


EventHelper1中的EventHelper2UserEvent.js始终为空(具有{}),其中EventHelper3被正确初始化并且能够正确引用对象的方法。我已将此全局变量EventHelper.js引用到其他控制器文件夹(EventController.js)中,并且已正确填充它。我不确定我是否想念这里的东西

最佳答案

您缺少一些分号:

function EventHelper() {
   this.onEventCreated = function(err, e) {...}
   this.isExisting = function(id) {...}
}**;**
module.exports = new EventHelper();


例如,添加此代码后,我在您的Controller中获得了EventHelper,这是我以前从未听说过的。

此外(我想这只是这里的错别字,而不是您的实际代码中的错字,因为那时您无法为其获取实例),它是:

EventHelper3.onEventCreated(err,e);


而不是

EventHepler3.onEventCreated(err,e);


综上所述,以下内容现在对我有用:

// EventHelper.js
function EventHelper() {
   this.onEventCreated = function(err, e) {
      console.log('testCreate');
   };
   this.isExisting = function(id) {
      console.log('testExists' + id);
      return true;
   };
};
module.exports = new EventHelper();

// UserEvent.js
var EventHelper1 = require('./EventHelper.js');
var EventHelper2 = require('./EventHelper.js');


function UserEvent() {
   this.fireEvent = function(req, res) {
      console.log(req + res);
      var EventHelper3 = require('./EventHelper');
      EventHelper1.onEventCreated(req, res);
      EventHelper2.onEventCreated(req, res);
      EventHelper3.onEventCreated(req, res);
   };
};
module.exports = new UserEvent();

// EventController.js
var EventHelper = require('../helpers/EventHelper.js');
var UserEvent = require('../helpers/UserEvent.js');

var EventController = {
   fireEvent: function(req, res) {
      if(EventHelper.isExisting(1)) UserEvent.fireEvent(req, res);
   };
 }

 EventController.fireEvent("1","2");


具有以下输出:

testExists1
12
testCreate
testCreate
testCreate


希望能对您有所帮助!

07-28 12:25