2013-08-20 23 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