困惑于需要JS

时间:2016-04-25 22:58:27

标签: javascript requirejs

考虑以下示例:

var ExampleFunction = function(param1, param2) {
   this.helloWorld = function() {
       console.log('hello world' + param1 + param2);
   }
}

当我做类似的事情时:

require(['https://path/to/example_function.js'], function(exampleFunction){
    console.log(exampleFunction);
});

我明白了:

define( function() { return function(param1, param2) {
    this.helloWorld = function() {
       console.log('hello world' + param1 + param2);
    }
} } );

如何注入此函数的依赖项?我似乎无法通过调用实例化我自己注入的函数。

当在本地加载时,我可以这样做:

var exampleFunction = new ExampleFunction(someParam, someOtherParam);

但是当我加载服务器时,我不能。

思想吗

2 个答案:

答案 0 :(得分:2)

如果您使用的是非RequireJS格式的脚本(包含在define()中),则必须在require配置中对它们进行填充,以便正确加载它们:

require.config({
    paths: {
        "exampleFunction": "https://path/to/example_function.js"
    },

    shim: {
        "exampleFunction":      {
            exports:    "exampleFunction"
        }
    }
});

然后像这样使用它们

require(["exampleFunction"], function(exampleFunction){
    new exampleFunction(param1, param2);
});

有关此主题的更多信息http://requirejs.org/docs/api.html#config-shim

答案 1 :(得分:1)

如果要将外部文件作为模块提供,请使用paths config。文件路径应该是无扩展名的。这是an example from the docs

requirejs.config({
    //To get timely, correct error triggers in IE, force a define/shim exports check.
    enforceDefine: true,
    paths: {
        jquery: [
            'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min',
            //If the CDN location fails, load from this location
            'lib/jquery'
        ]
    }
});

//Later
require(['jquery'], function ($) {

});
相关问题