6

我需要在浏览器中使用Q库(http://documentup.com/kriskowal/q/ )。我想RequireJS用来加载这个库,但我不知道如何做到这一点。我知道如何加载我自己的模块,但我不能用Q. 它有一些功能:

(function (definition) { 
  //some another code here***
  // RequireJS
} else if (typeof define === "function" && define.amd) {
  define(definition);

如何加载Q然后在另一个模块中使用它?

4

2 回答 2

14

正确的 AMD 方法是(借用 @Eamonn O'Brien-Strain 的示例代码):

requirejs.config({
  paths: {
    Q: 'lib/q'
  }
});

function square(x) {
  return x * x;
}

function plus1(x) {
  return x + 1;
}

require(["Q"], function (q) {
  q.fcall(function () {
    return 4;
  })
    .then(plus1)
    .then(square)
    .then(function (z) {
      alert("square of (value+1) = " + z);
    });
});

这种方式Q不会泄漏到全局范围,并且很容易找到依赖于这个库的所有模块。

于 2013-09-16T11:59:07.880 回答
3

您可以使用 HTML 中的脚本语句简单地加载 Q 库

<script src="https://cdnjs.cloudflare.com/ajax/libs/q.js/1.1.0/q.js"></script>

然后你可以Q像这样通过变量访问它:

function square(x) {
    return x * x;
}
function plus1(x) {
    return x + 1;
}

Q.fcall(function () {return 4;})
.then(plus1)
.then(square)
.then(function(z) {
    alert("square of (value+1) = " + z);
});

在http://jsfiddle.net/Uesyd/1/看到这个运行

于 2013-08-20T06:14:22.943 回答