require.js如何实现循环依赖的?
可否写两个闭包,说明一下其中的原理?

解决方案 »

  1.   

    $(function(){
    define("aa",["bb"],function(bb){
    return {aa:3}
    });
    define("bb",["aa"],function(aa){
    return {bb:aa.aa}
    });
    require(["bb"],function(bb){
       window.alert(bb.bb);
    });  
    });  比如上面的代码,在require.js中是完全没有问题的
    不知他是怎么实现的
      

  2.   

    require不是开源吗?你下个未压缩的研究研究
      

  3.   

    http://stackoverflow.com/questions/4881059/how-to-handle-circular-dependencies-with-requirejs-amd
    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;
    });用exports来解决这个问题
      

  4.   


    答非所问,我在上面的示例代码已经说明,不用exports,也能实现循环依赖,是怎么做到的
      

  5.   

    老哥多看api啊 requirejs没有直接实现 但是有官方api需要自己手动实现的
    Circular Dependencies
    § 1.3.8
    If you define a circular dependency ("a" needs "b" and "b" needs "a"), then in this case when "b"'s module function is called, it will get an undefined value for "a". "b" can fetch "a" later after modules have been defined by using the require() method (be sure to specify require as a dependency so the right context is used to look up "a"):
    //Inside b.js:
    define(["require", "a"],
        function(require, a) {
            //"a" in this case will be null if "a" also asked for "b",
            //a circular dependency.
            return function(title) {
                return require("a").doSomething();
            }
        }
    );
    翻一下就是
    如果你定义了一个循环依赖(a依赖b,b同时依赖a),则在这种情形下当b的模块函数被调用的时候,它会得到一个undefined的a。b可以在模块已经定义好后用require()方法再获取a(记得将require作为依赖注入进来):
    //b.js:
    define(["require", "a"],
        function(require, a) {
            //"a"将是null,如果a/b间是循环依赖
            return function(title) {
                return require("a").doSomething();
            }
        }
    );
    就是类似于commenjs的依赖就近