2013-08-20 19 views
6

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

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

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

回答

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/

+6

尽管这样可行,但我认为这是一个坏主意,因为这意味着您将混合使用模块化(即AMD/RequireJS)和“传统”(即全局变量)代码,从长远来看可能会导致问题。 – kryger

+0

https://rawgithub.com/kriskowal/q/master/q.js - 未找到 –

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不会泄漏到全局范围,并且很容易根据这个库找到所有模块。

+1

可能它也需要垫片结构中的条目,因为它不是AMD模块: 'shim:{0} {0} {0} {0} :{ 出口:'Q' } }'' – marcos82