【问题标题】:In Dojo, why require() a module that's already been defined()?在 Dojo 中,为什么需要()一个已经定义()的模块?
【发布时间】:2013-05-17 13:26:59
【问题描述】:

我正在查看另一个人编写的 JavaScript sn-p,它说,

define(
    [
        "dojo/a",
        "dojo/b",
        "dojo/c",
        ...,
        "dojo/z"
    ],
    function(a, b) {
        var c = require("dojo/c");
        ...;
        var z = require("dojo/z");

        // code goes here
    }
);

我正试图弄清楚你为什么要这样做。这么短的sn-p是不是一模一样?:

define(
    [
        "dojo/a",
        "dojo/b",
        "dojo/c",
        ...,
        "dojo/z"
    ],
    function(a, b, c, ..., z) {
        // code goes here
    }
);

【问题讨论】:

  • 我倾向于同意;该代码对我来说没有意义。

标签: javascript dojo js-amd


【解决方案1】:

导入一次模块后无需再次添加require:

<script>require(['dojox/rpc/JsonRPC','dojo/store/Memory','dijit/form/FilteringSelect'],
        function(FilteringSelect,JsonRPC,Memory){

        ##your code goes here..

        });
</script>

【讨论】:

    【解决方案2】:

    在你的第一个sn-p中sn-ps不一样,加载器首先将数组中传递的所有模块加载到require,并且只有在加载了数组中列出的所有模块后才执行回调。在回调中,您可以在其他代码之前运行其他代码 require

    例子:

    define(
        [
            "dojo/a",
            "dojo/b",
            "dojo/c",
            ...,
            "dojo/z"
        ],
        function(a, b) {
            // execute some code here
            var c = require("dojo/c");
            var z = require("dojo/z");
            // code execute here even if c and z are not loaded yet
        }
    );
    

    你的第二个 sn-p 回调仅在所有模块都加载时执行。

    通常我会选择第二种方法,即使如果您需要根据某些条件加载一些模块,第一种方法可能会很方便。

    【讨论】:

      猜你喜欢
      • 2012-09-20
      • 2015-06-24
      • 2020-02-14
      • 2014-01-24
      • 1970-01-01
      • 2019-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多