我正在使用backbone.js和require.js。我尝试了一个教程,这是我的index.html:
<script src="app/script/libs/require/require.js" data-main="app/script/main" type="text/javascript"></script>
<script src="app/script/router.js" type="text/javascript"></script>
<script type='text/javascript'>
$(document).ready(function()
{
var appRouter = new AppRouter(); // Router initialization
Backbone.history.start(); // Backbone start
});
</script>
这是main.js:
require.config({
urlArgs: "bust=" + (new Date()).getTime(),
paths: {
jquery: 'libs/jquery/jquery',
underscore: 'libs/underscore/underscore',
backbone: 'libs/backbone/backbone'
}
});
require(["jquery", "underscore", "backbone"],
function ($, _, Backbone) {
console.log("Test output");
console.log("$: " + typeof $);
console.log("_: " + typeof _);
console.log("Backbone: " + typeof Backbone);
}
);
这是我的控制台:
ReferenceError: Backbone is not defined
[Break On This Error]
$(document).ready(function()
ReferenceError: $ is not defined
[Break On This Error]
$(document).ready(function()
Test output
$: function
_: function
Backbone: object
Require.js正在运行,但是主干和jquery未定义,我不知道它们有什么问题。
这是我文件的结构:
请问任何想法。感谢
答案 0 :(得分:2)
您还应该在shim config
中声明您的图书馆require.config({
urlArgs: "bust=" + (new Date()).getTime(),
paths: {
jquery: 'libs/jquery/jquery',
underscore: 'libs/underscore/underscore',
backbone: 'libs/backbone/backbone'
},
shim: {
'backbone': {
deps: ["underscore", "jquery"],
exports: "Backbone"
},
'underscore': {
exports: "_"
}
}
});
require(["jquery", "underscore", "backbone"],
function ($, _, Backbone) {
console.log("Test output");
console.log("$: " + typeof $);
console.log("_: " + typeof _);
console.log("Backbone: " + typeof Backbone);
}
);
答案 1 :(得分:1)
使用您的设置,只有当它在requireJS模块中作为依赖项注入时才能使用Backbone,它在全局名称空间中不可用。在jquery,Backbone或下划线等大多数模块中也需要你需要的东西似乎不是最好的主意。只需将它们作为脚本标记加载到requireJS主文件之前,一切都很好。
如果你想保留垫片解决方案,你必须在main.js文件中启动你的应用程序
require.config({
urlArgs: "bust=" + (new Date()).getTime(),
paths: {
jquery: 'libs/jquery/jquery',
underscore: 'libs/underscore/underscore',
backbone: 'libs/backbone/backbone'
}
});
require(["jquery", "underscore", "backbone"],
function ($, _, Backbone) {
console.log("Test output");
console.log("$: " + typeof $);
console.log("_: " + typeof _);
console.log("Backbone: " + typeof Backbone);
$(document).ready(function() {
var appRouter = new AppRouter(); // Router initialization
Backbone.history.start(); // Backbone start
});
}
);