2

我有一个非 AMD javascript,其中包含我的自定义函数,例如:

function getItemIndexById(items, id){
   for(var i = 0; i < items.length; i++){
       if(items[i].ID == id) return i;
   }
   return false;
}
//more than one define custom function here.

这里 main.js 文件:

requirejs.config({
 enforceDefine: true,
 paths: {
    "jquery": "libs/jquery/jquery-min",
    "underscore": "libs/underscore/underscore-min",
    "backbone": "libs/backbone/backbone-min",
    "custom" : "libs/scripts/customejs"
},
shim: {
    "underscore": {
        deps: [],
        exports: "_"
    },
    "backbone": {
        deps: ["jquery", "underscore"],
        exports: "Backbone"
    }
}
});

然后我在我的视图中定义:

define(["jquery" ,
        "underscore" ,
        "backbone" ,
        "custom"
],function($ , _ , Backbone, Custom){
  //.....
}

我在Uncaught Error: No define call for custom.

我必须将我的自定义 js 转换为 AMD 吗?谁能解释一下这个问题。谢谢。

4

1 回答 1

8

Require 文档中描述了此问题的几个常见原因。

在这种情况下,很可能是因为您正在使用enforceDefine: true并且“自定义”js 文件没有调用define().

您将需要enforceDefine: false为自定义代码设置或添加适当的垫片。

shim 的目的是允许 Require 加载非 AMD 代码。它通过加载代码并验证脚本是否在全局空间中创建了由属性定义的exports属性来工作。

在您的情况下,您可以将getItemIndexById其用作exports值:

shim: {
   "custom": {
      exports: "getItemIndexById"
   }

当您用作Customexports时,它不起作用,因为您的脚本没有创建一个名为Custom

阅读更多关于shim 这里

于 2013-10-02T03:22:23.960 回答