1

我正在尝试在我的非 AMD 要求应用程序中使用一个库——谷歌的 libphonenumber 。吃这个的最好方法是什么?我知道我可以创建这样的模块:

define(['module'], function (module) {
    // insert and return library code here.
});

但这似乎不太好。似乎我必须重构他们的一些代码才能使其正常工作(例如,将其全部转换为对象并返回该对象)。我看到很多库使用不同的模式,它们使用立即调用的函数,该函数在窗口对象上定义模块并返回它。

(function() {

    var phoneformat = {};

    window.phoneformat = phoneformat;

    if (typeof window.define === "function" && window.define.amd) {
        window.define("phoneformat", [], function() {
            return window.phoneformat;
       });
    }

})();

** 更新 ** 有什么理由不这样做吗?

define(['lib/phoneformatter'], function(phoneformatter) {

});

我可以访问我的所有方法,但现在它们似乎是全局的,因为我没有将库包装在定义中......

4

2 回答 2

3

使用 RequireJS 的shim。它看起来像这样

requirejs.config({
  shim: {
    'libphonenumber': {
      exports: 'libphonenumber' // Might not apply for this library
    }
  }
});

这将加载libphonenumber并将其变量放在全局范围内

于 2014-06-30T19:01:30.417 回答
2

这最终为我工作:

define(['module'], function (module) {
    // insert and return library code here.
});

我不完全确定为什么需要“模块”。但没有它就行不通。另外,我刚刚返回了一个对象并为其附加了函数,如下所示:

return {
    countryForE164Number: countryForE164Number,
    nextFunction: nextFunction,
    // more functions as needed.
}

使用“模块”的文档方式并不多,但据我所知:模块是由 requireJS 核心处理的特殊依赖项。它为您提供有关当前模块的模块 ID 和位置的信息。所以我完全有可能搞砸了 config.xml 中的路径。

于 2014-07-02T17:59:02.250 回答