我不断收到 index.js:7 Uncaught TypeError: Cannot read property 'View' of null
,这表明 Backbone 没有加载/存在,但是,当我查看加载的资源时在页面上 backbone-min.js 存在。
由于没有 404 错误,我认为问题出在脚本本身。有没有人看到下面的脚本有任何问题?
注意:为方便起见,我上传了我的代码 here . zip 文件包含所有相关的 js 文件。如果你滚动到网页的底部,你应该看到一个“慢 下载”按钮,一旦你点击它,你会被提示输入一个 图形验证码。输入代码后,实际下载按钮 (在“慢速下载”按钮下)将在几秒钟内出现。
View :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();
});
最佳答案
所以这个问题的关键是underscore.js的变化。特别是它现在支持 AMD(异步模块定义)。当检测到 require 时,下划线不再将自身附加到全局命名空间这一事实打破了用于允许标准异步 require 语法但仍保持同步加载的方案。
既然 JQuery、Underscore 和 Backbone(0.5.3 没有自行注册,你需要 a this )支持异步加载,你就可以放弃那些被黑的库,转而使用标准库,并要求这些库注册的名称自己与。像这样:
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...");
});
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();
});
其他定义已更改以反射(reflect)新的小写别名。
拉取固定码here
关于javascript - 无法创建主干 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8069865/