小编典典

如何使用RequireJS / AMD处理循环依赖关系?

javascript

在我的系统中,我在浏览器中加载了许多“类”,在开发过程中,每个类都有单独的文件,并串联在一起进行生产。加载它们时,它们在全局对象(这里)上初始化一个属性G,如以下示例所示:

var G = {};

G.Employee = function(name) {
    this.name = name;
    this.company = new G.Company(name + "'s own company");
};

G.Company = function(name) {
    this.name = name;
    this.employees = [];
};
G.Company.prototype.addEmployee = function(name) {
    var employee = new G.Employee(name);
    this.employees.push(employee);
    employee.company = this;
};

var john = new G.Employee("John");
var bigCorp = new G.Company("Big Corp");
bigCorp.addEmployee("Mary");

我考虑使用James Burke的建议,而不是使用自己的全局对象,而是考虑使每个类都具有自己的AMD模块:

define("Employee", ["Company"], function(Company) {
    return function (name) {
        this.name = name;
        this.company = new Company(name + "'s own company");
    };
});
define("Company", ["Employee"], function(Employee) {
    function Company(name) {
        this.name = name;
        this.employees = [];
    };
    Company.prototype.addEmployee = function(name) {
        var employee = new Employee(name);
        this.employees.push(employee);
        employee.company = this;
    };
    return Company;
});
define("main", ["Employee", "Company"], function (Employee, Company) {
    var john = new Employee("John");
    var bigCorp = new Company("Big Corp");
    bigCorp.addEmployee("Mary");
});

问题在于,以前在Employee和Company之间没有声明时间依赖关系:您可以按所需的顺序放置声明,但是现在,使用RequireJS引入了依赖关系,在这里(有意地)是循环的,因此以上代码失败。当然,在addEmployee()补充一线varEmployee =require("Employee");将使它的工作,但我看到这个解决方案,不如不使用RequireJS
/ AMD,因为它需要我,开发商,要知道这个新创建循环依赖,并做一些事情。

是否有更好的方法来解决RequireJS / AMD的问题,还是我将RequireJS / AMD用于并非为它设计的东西?


阅读 493

收藏
2020-05-01

共1个答案

小编典典

这确实是AMD格式的限制。您可以使用导出,该问题就消失了。我发现导出很丑陋,但这是常规CommonJS模块如何解决此问题的方法:

define("Employee", ["exports", "Company"], function(exports, Company) {
    function Employee(name) {
        this.name = name;
        this.company = new Company.Company(name + "'s own company");
    };
    exports.Employee = Employee;
});
define("Company", ["exports", "Employee"], function(exports, Employee) {
    function Company(name) {
        this.name = name;
        this.employees = [];
    };
    Company.prototype.addEmployee = function(name) {
        var employee = new Employee.Employee(name);
        this.employees.push(employee);
        employee.company = this;
    };
    exports.Company = Company;
});

否则,您在消息中提到的require(“ Employee”)也将起作用。

通常,对于模块,您需要更加了解循环依赖性,无论是否存在AMD。即使在普通的JavaScript中,也必须确保在示例中使用类似G对象的对象。

2020-05-01