2017-02-14 102 views
0

的文件說,一旦underscore.string包括在我的應用程序,該庫可使用小號__s全局變量(http://epeli.github.io/underscore.string/#others),或在下劃線屬性__。str__。string如何使用網頁全球underscore.string(與requireJS)

這個簡單的代碼都正常工作(用正確的設置配置路徑):

require(['underscore','underscore.string'], function(){ 
    console.log(s('test').capitalize().value()); 
}); 

不過,這並不在所有的工作。這是一個簡單的jsfiddle示例。我可能做錯了什麼,但我無法弄清楚什麼。

https://jsfiddle.net/mvenrtgy/10/

相關的測試代碼:

require.config({ 
    paths: { 
    'underscore':'https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min', 
    'underscore.string':'https://cdnjs.cloudflare.com/ajax/libs/underscore.string/3.3.4/underscore.string.min' 
    } 
}); 
require(['underscore','underscore.string'], function(){ 

    var t = 'This is a simple text I would like to SLUGIFY using unsercore.string'; 

    // underscore is there! 
    console.log(typeof _) 

    // now check where underscore.string is... 
    console.log(typeof _.str); 
    console.log(typeof _.string); 
    console.log(typeof s); 
    console.log(typeof _s); 

    document.getElementsByTagName('body')[0].innerHTML = '<p>Sample text : ' + t + '</p>'; 
    // this line will cause an error 
    document.getElementsByTagName('body')[0].innerHTML += '<p><em>Slugified</em> text : ' + s(t).slugify().value() + '</p>'; 


}); 

回答

0

underscore.string是一個乖巧的AMD庫,所以它不會影響全局空間。你應該改變你的require電話,以便使其到達對應於正在加載的模塊的參數:

require(['underscore','underscore.string'], function(_, s){ 

通過只是讓這改變了代碼,我得到的一些作品。測試2號線出現爲:

Slugified文本:這 - 是 - 一 - 簡單的文本-I-將樣到使用-unsercore slugify-串

此外,雖然underscore.string開始underscore擴展,發展已​​經超出了,這樣你就可以不通過_全球是underscore泄漏訪問到全球空間,除非你採取與underscore混合它的照顧。該documentation說,你可以這樣做:

_.mixin(s.exports()); 

但文檔建議反對票,因爲underscore.string將一些基本的功能是underscore出口干擾。請自擔風險使用。

+0

當然,我知道我們可以在下劃線內混合使用,但是我真的不希望稍後因爲下劃線干擾而陷入困境。在require調用中,我也不能像你所建議的那樣使用它,因爲我實際上需要在下劃線/骨幹模板系統中使用backbone.string函數。我忘了提到抱歉。因此,下劃線模板引擎僅適用於全局變量/函數。我別無選擇,只能找到一種方法讓underscore.string可以全局訪問.... – Simmoniz