2014年在RequireJS中使用Backbone, Underscore和jQuery的依赖
Dependencies in RequireJS with Backbone, Underscore, and jQuery in 2014
我看到了很多关于使用RequireJS/Backbone、Underscore和jQuery的问题。我的问题略有不同;我的应用程序可以运行,但我不知道为什么。
目前,Underscore, jQuery和Backbone都导出AMD模块,所以我不需要再对它们进行shim和导出它们的变量。因此,我的main.js
看起来像下面的代码片段。
main.js
require.config({
paths: {
jquery: 'lib/jquery/jquery-1.10.2',
'jquery-ui': 'lib/jquery/jquery-ui-1.10.4.min',
underscore: 'lib/underscore/underscore.min',
backbone: 'lib/backbone/backbone.min',
'backbone.localStorage': 'lib/backbone/backbone.localStorage'
}
});
require(['jquery', 'jquery-ui', 'underscore', 'backbone', 'backbone.localStorage'], function() {
});
require.html
<!DOCTYPE html>
<html>
<head>
<title>My Sample Project</title>
<!-- data-main attribute tells require.js to load
scripts/main.js after require.js loads. -->
</head>
<body>
<h1>My Sample Project</h1>
<div id="test"> </div>
<script type="text/javascript" data-main="js/main" src="js/lib/require/require.js"></script>
<script type="text/javascript">
</script>
</body>
</html>
当我转到require.html
时,我可以转到控制台,所有变量都正确加载在那里。例如,var x = Backbone.Model.extend({}); var y = new x;
工作得很好。但是,Backbone同时依赖于Underscore和jQuery。RequireJS是否使用这些库提供的模块自动解决这些依赖关系,或者它只是作为一个侥幸?
你有require
后需要配置设置
require(['jquery', 'jquery-ui', 'underscore', 'backbone', 'backbone.localStorage'], function() {
});
它们以正确的顺序加载偶然,为了控制这个顺序,你需要定义每个模块的依赖关系在shim
Require对这类工作有很大帮助。
你可以使用'shim'命令以一种简单而正确的方式指定依赖项,就像这样。
//Coffeescript example
paths:
backbone : 'path/backbone'
underscore : 'path/underscore'
jquery: 'path/jquery'
shim:
backbone:
deps:['underscore','jquery']
exports: 'Backbone'
这样你就可以定义,当一个名为'Backbone'的模块被调用时,require会加载deps:[]中的所有依赖项。现在它将永远不会在下划线之前加载主干。
我有一个关于它的博客和一篇文章,不幸的是它只有葡萄牙语,但也许有帮助。
http://www.rcarvalhojs.com/backbone/2014/06/03/comecando-require-backbone.html相关文章:
- 无法从 jQuery RSS Feed 中的 localStorage 动态替换类
- Backbone.js 不起作用,而 Underscore、JSON 和 jQuery 可以
- 如何在 Backbone / Underscore 上应用 jQuery timeago 或 easydate
- JQuery 或 Underscore 等同于 JavaScript 的 hasOwnProperty
- 要求.js jquery/underscore/backbone/parse 模块的加载超时
- 使用 RequireJS 2.0.1 和填充码加载 jQuery、Underscore 和 Backbone
- 如何让 jQuery 与 Underscore 一起工作
- jQuery.proxy vs. underscore.bind
- Underscore bind vs jQuery.proxy vs Native bind
- 使用jQuery或Underscore.js获取嵌套对象中字段的值
- 使用Underscore.js或jQuery-JavaScript将对象数组转换为逐字段数组
- Throttle Jquery UI拖动事件侦听器,并使用underscore.js或其他实现传递参数
- underscore.js模板中的JQuery事件
- 使用jQuery或underscore.js合并对象中多个数组的值
- 是否有任何jQuery构建可用's经过优化,可与underscore.js一起使用
- 在jquery对象的集合上使用underscore.js列表函数
- 使用require.js将jQuery、Underscore和Backbone作为AMD模块的最佳方式是什么?
- jQuery won't bind使用.on()对通过函数添加的项使用click to underscore模板
- 2014年在RequireJS中使用Backbone, Underscore和jQuery的依赖
- 转换 jQuery 对象中的 lodash/underscore 集合(链接)