是否可以从另一个函数调用一个函数? (保留单独的文件)

时间:2013-07-09 08:59:16

标签: requirejs

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

Main.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;
})

two.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;
})

为什么我收到此错误?

1 个答案:

答案 0 :(得分:2)

问题在于您创建了circular dependency

在这种情况下,只有一个注入的值具有正确的值,另一个值是未定义的。如果你想一想,它清楚地知道这个不能工作,会导致第二个注入的那个应该如何知道第二个,因为在创建第一个时不会创建第二个。

幸运的是,有一个解决方案。使用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'