Dan*_*Dan 3 javascript requirejs backbone.js
我不断得到index.js:7 Uncaught TypeError: Cannot read property 'View' of null,这表明Backbone没有加载/存在,但是,当我查看页面上的加载资源时,我发现了min.js.
由于没有404错误,我认为问题在于脚本本身.有没有人看到下面的脚本有任何问题?
注:为了方便我上传我的代码在这里.zip文件包含所有相关的js文件.如果滚动到网页底部,您会看到"慢速下载"按钮,单击它后,系统会提示您输入验证码.输入代码后,实际下载按钮(在"慢速下载"按钮下)将在几秒钟内出现.
查看:index.js
define([
"jQuery",
"Underscore",
"Backbone"
// I've tried using the modules above as well as direct loading using order! as seen in the following lines.
//"order!libs/jquery/jquery-min",
//"order!libs/underscore/underscore-min",
//"order!libs/backbone/backbone-min",
],
function($, _, Backbone){
console.log(_) // prints "undefined"
console.log(Backbone) // prints Object
var IndexView = Backbone.View.extend({ // At this line I now get: Uncaught TypeError: Cannot call method 'extend' of undefined
render: function(){
$(this.el).html("<h1>Welcome Dan!</h1>");
$("body").html(this.el);
}
});
return new IndexView();
});
Run Code Online (Sandbox Code Playgroud)
所以这个问题的关键是underscore.js的变化.特别是它现在支持AMD(异步模块定义).当检测到require时,下划线不再将自身附加到全局命名空间这一事实打破了用于允许标准异步require语法但仍保持同步加载的方案.
现在,JQuery的,下划线和骨干网(0.5.3不注册本身,你需要一本)支持异步加载,你可以抛弃那些黑客库支持通用的标准,并要求这些图书馆与自己注册的名字.像这样:
Main.js
require.config({
baseUrl: "js",
paths: {
jquery: "libs/jquery/jquery",
underscore: "libs/underscore/underscore",
backbone: "libs/backbone/backbone"
},
waitSeconds: 10
});
require([
"app"
],
function(App){
App.initialize();
console.log("Main initialized...");
});
Run Code Online (Sandbox Code Playgroud)
index.js
define([
"jquery",
"underscore",
"backbone"
],
function($, _, Backbone){
console.log(_);
console.log(Backbone);
var IndexView = Backbone.View.extend({
render: function(){
var username = getCookie("username");
var data = {username: username};
var compiled = _.template("<h1>Welcome <%= username %></h1>", data);
$(this.el).html(compiled);
$("#lt-col").html(this.el);
}
});
return new IndexView();
});
Run Code Online (Sandbox Code Playgroud)
其他定义被更改以反映新的小写别名.
在这里拉固定代码