简体   繁体   English

node.js导出方法外观设计模式

[英]node.js exporting methods facade design pattern

I am trying to follow the facade design pattern in a node.js application where I have on object that is used with the rest of the application called controller.js as the facade. 我正在尝试在node.js应用程序中遵循外观设计模式,我在该对象上使用了与其余应用程序称为controller.js的外观一起使用的对象。 The controller controls calls to objects user.js, animal.js, and house.js which are all separate files. 控制器控制对对象user.js,animal.js和house.js的调用,这些对象都是单独的文件。

In controller.js I do 在controller.js中

var housecontroller = require("./controllers/housecontroller");
...

I want to call something like controller.getHouse() in another file (client). 我想在另一个文件(客户端)中调用类似controller.getHouse() )的名称。 How do I make it so that I can do that and not have to call housecontroller.getHouse() ? 我如何做到这一点,而不必调用housecontroller.getHouse()

Each of my controllers are formatted as follows 我的每个控制器的格式如下

module.exports = {
    getHouse:function(){...},
    ...
}

I'm a bit confused on how to properly export things in order to get this to work. 我对如何正确导出内容以使其正常工作感到困惑。 I import/export the controllers and their methods in controller.js as follows 我在controller.js中导入/导出控制器及其方法,如下所示

module.exports = {
    getHouse : housecontroller.getHouse,
    ...
};    

I use only the house in the examples but it's implied I do the same for user and animal which all have several methods. 在示例中,我仅使用房屋,但这意味着我对用户和动物都使用相同的方法,它们都有几种方法。 In the client, I just import controller.js and use its methods. 在客户端中,我只导入controller.js并使用其方法。

var controller = require("./controller");
controller.getHouse();

According to your code/naming you could have a file controller.js in controllers folder with something like this 根据您的代码/命名,您可以在controllers文件夹中包含一个类似以下内容的controller.js文件

var housecontroller = require('./housecontroller');
var carcontroller = require('./carcontroller');

module.exports = {
  getHouse: housecontroller.controller,
  getCar: carcontroller.controller
};

The client code could be: 客户端代码可以是:

var controller = require('./controllers/controller');
controller.getHouse();

I added carcontroller as example of extension. 我添加了carcontroller作为扩展示例。

If you only have one function to offer from each controller you can change your code and these examples to: 如果每个控制器只能提供一个功能,则可以将代码和这些示例更改为:

//housecontroller.js
module.exports = getHouse;

//controller.js
var housecontroller = require('./housecontroller');
var carcontroller = require('./carcontroller');

module.exports = {
  getHouse: housecontroller,
  getCar: carcontroller
};

Although I don't recommend it because you are reducing the opportunity to offer more functions from that module in the future 尽管我不建议这样做,因为您将来会减少从该模块提供更多功能的机会

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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