0

我知道我可以随时调用任何文件来调用其功能(如果我错了,请纠正我)。我决定通过创建两个模块()来测试这一点,并从一个调用嵌套在两个中的函数。这可行,但我无法从函数二调用函数

主.js

requirejs.config({
  baseUrl: "js"
});

require([
  "script/one"
], function ($, $Ui, hBs, one) {
  //works fine
  one.get("I am the initiator");
});

one.js

define(['script/two'], function (two) {
  var one = function () {
    return {
      get: function (msg) {
        //works
        console.log("get: " + msg);
        //works fine    
        two.serve1("I am from one of one");
      },
      post: function (msg) {
        // i am calling this method from two.js
        console.log("post: " + msg);
        two.serve2("i am from two of two");
      }
    }

  }
  return new one;
})

二.js

define([ 'require', 'script/one'], function (require,one) {
  var two = function () {
     one = require('script/one'); // throwing error as "Uncaught Error: Module name "script/one" has not been loaded yet for context: _"
    return {
      serve1: function (msg) {
        console.log("2 in serve1 :" + msg)
        // calling doesn't
        one.post("initiated from one, called in two");
        // throws "Uncaught TypeError: Cannot call method 'post' of undefined"
      },
      serve2: function (msg) {
        console.log("2 in serve2 :" + msg)
      }
    }
  }
  return new two;
})

为什么我会收到此错误?

4

1 回答 1

2

问题是您创建了一个循环依赖项

在这种情况下,只有一个注入的值具有正确的值,另一个是未定义的。如果您考虑一下,很明显这是行不通的,因为在创建第一个时,注入第二个的应该如何知道第二个,因为他不是创建的。

幸运的是,有一个解决方法。稍后使用该require函数加载依赖项:

define(["require", 'script/one'], function (require, one) {
  var two = function () {
    return {
      serve1: function (msg) {
        one = require('script/one');
        console.log("2 in serve1 :" + msg)
        // calling doesn't
        one.post("initiated from one, called in two");
        // throws "Uncaught TypeError: Cannot call method 'post' of undefined"
      },
      serve2: function (msg) {
        console.log("2 in serve2 :" + msg)
      }
    }
  }
  return new two;
})

请注意,您仍然需要'script/one'在依赖数组中引用 to。

于 2013-07-09T12:33:56.310 回答