Tru*_*an1 11 javascript asynchronous dynamic-script-loading requirejs underscore.js
在加载时,在Underscore上执行代码的正确方法是什么?我正在尝试执行以下代码,以便在模块需要时自动扩展_ exported namespace:
_.mixin(_.str.exports());
Run Code Online (Sandbox Code Playgroud)
文档有点模糊,但我想我把它放在shim init部分?我试过以下但是我甚至无法在init中获得一个断点:
require.config({
paths: {
jquery: 'libs/jquery/jquery.min',
underscore: 'libs/underscore/lodash.min',
underscorestring: 'libs/underscore/underscore.string.min'
},
shim: {
underscore: {
exports: '_'
}
underscorestring: {
deps: ['underscore'],
init: function (_) {
//Mixin plugin to namespace
_.mixin(_.str.exports());
return _;
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
当我尝试这样做并使用underscorestring时,我收到此错误:
未捕获的TypeError:对象函数s(e){return new o(e)}没有方法'startsWith'
文档:
Gar*_*son 19
我不知道它是否是正确的方法,但我通过反转来使其工作,以便下划线取决于underscore.string.此外,这种方式您不必要求underscore.string.
require.config({
shim: {
'backbone': {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
},
'underscore': {
deps: ['underscore.string'],
exports: '_',
init: function(UnderscoreString) {
_.mixin(UnderscoreString);
}
}
},
paths: {
'backbone' : 'lib/backbone',
'jquery' : 'lib/jquery/jquery',
'text' : 'lib/require/text',
'underscore' : 'lib/underscore',
'underscore.string' : 'lib/underscore.string'
}
});
Run Code Online (Sandbox Code Playgroud)
.
更新:2014年3月14日
Underscore.js v1.6.0带回了AMD兼容性,init()并已从RequireJS中删除,因此有些重构是有序的.要继续使用Underscore.string预先加载Underscore,我制作了一个混音器模块将它们组合在一起.
新的Require.js配置
requirejs.config({
paths: {
'backbone' : '../lib/backbone/backbone',
'backbone.base' : '../lib/backbone/backbone.base',
'backbone.extensions' : '../lib/backbone/backbone.extensions',
'jquery' : '../lib/jquery/jquery',
'text' : '../lib/require/text',
'underscore' : '../lib/underscore/underscore',
'underscore.mixed' : '../lib/underscore/underscore.mixed',
'underscore.string' : '../lib/underscore/underscore.string'
},
shim: {
'backbone.base': {
deps: ['underscore.mixed', 'jquery'],
exports: 'Backbone'
},
}
});
Run Code Online (Sandbox Code Playgroud)
underscore.mixed
define([
'underscore',
'underscore.string'
], function(_, _s) {
_.mixin(_s.exports());
return _;
});
Run Code Online (Sandbox Code Playgroud)
最后一步是替换的所有实例'underscore'与'underscore.mixed'模块定义.我试图将Underscore移动到一个名为的文件中underscore.base.js并使常规underscore混合器(如Backbone设置)以避免这一步骤.作为一个命名模块的下划线不同意该计划.