如何在网页中全局使用下划线.string(使用requireJS)

如何在网页中全局使用下划线.string(使用requireJS),requirejs,underscore.js,underscore.string.js,Requirejs,Underscore.js,Underscore.string.js,文档中说,一旦我的应用程序中包含下划线.string,就可以使用s、\uuuu s全局变量()或下划线属性\uuuuuu.str或\uuuuuuu.string使用该库 然后,此简单代码应能正常工作(正确设置了配置路径): 但它根本不起作用。下面是一个简单的JSFIDLE示例。我可能做错了什么,但我不知道是什么 相关测试代码为: require.config({ paths: { 'underscore':'https://cdnjs.cloudflare.com/ajax/lib

文档中说,一旦我的应用程序中包含下划线.string,就可以使用s\uuuu s全局变量()或下划线属性\uuuuuu.str\uuuuuuu.string使用该库

然后,此简单代码应能正常工作(正确设置了配置路径):

但它根本不起作用。下面是一个简单的JSFIDLE示例。我可能做错了什么,但我不知道是什么

相关测试代码为:

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>';


});
require.config({
路径:{
“下划线”:”https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min',
'下划线.string':'https://cdnjs.cloudflare.com/ajax/libs/underscore.string/3.3.4/underscore.string.min'
}
});
require(['underline','underline.string'],function()){
var t='这是一个简单的文本,我想使用unsercore.string'来对其进行slagify;
//在那里!
console.log(类型为
//现在检查下划线.string的位置。。。
console.log(类型为u.str);
console.log(类型为u.string);
控制台日志(类型s);
控制台日志(类型);
document.getElementsByTagName('body')[0]。innerHTML='示例文本:'+t+'

'; //此行将导致错误 document.getElementsByTagName('body')[0].innerHTML+='slagified文本:'+s(t).slagify().value()+'

'; });
下划线.string是一个性能良好的AMD库,因此不会污染全局空间。您应该更改
require
调用,以便它获取与正在加载的模块相对应的参数:

require(['underscore','underscore.string'], function(_, s){
通过对代码进行更改,我得到了一些有用的东西。您测试的第二行显示为:

Slugified text:this-is-a-simple-text-i-will-like-to-slugify-using-unsercore-string

另外,虽然
下划线.string
下划线
扩展名开始,但它已经扩展到了该扩展名之外,因此您无法通过
下划线
泄漏到全局空间的
全局访问它,除非您注意将其与
下划线
混合使用。上面说你可以这样做:

_.mixin(s.exports());

但是文档建议不要使用它,因为
下划线.string
会干扰
下划线
导出的一些基本函数。使用风险自负。

我当然知道我们可以在下划线中混合使用,但我真的不想以后因为下划线的干扰而陷入麻烦。我也不能像您建议的那样在require调用中使用它,因为我实际上需要在下划线/主干模板系统中使用backbone.string函数。我忘了说对不起。因此,下划线模板引擎仅适用于全局变量/函数。我别无选择,只能找到一种使下划线.string全局可访问的方法。。。。
_.mixin(s.exports());