这是我第一次将require.js与骨干一起使用,我很难在我的观点中找到问题:
Cannot read property 'View' of undefined // search.js:8
我的目录结构是:
.
├── index.php
└── js
├── app.js
├── lib
│ ├── backbone.js
│ ├── backbone-min.js
│ ├── jquery-min.js
│ ├── require.js
│ └── underscore-min.js
├── main.js
├── model
├── router.js
├── text.js
└── view
├── error.js
└── search.js
我的main.js
:
require.config({
paths: {
jquery: 'lib/jquery-min',
underscore: 'lib/underscore-min',
backbone: 'lib/backbone-min',
templates: '../templates'
}
});
require([
'app'
], function(App){
App.initialize();
});
我的app.js
:
define([
'jquery',
'underscore',
'backbone',
'router', // Request router.js
], function($, _, Backbone, Router){
var initialize = function(){
// Pass in our Router module and call it's initialize function
Router.initialize();
}
return {
initialize: initialize
};
});
我的router.js
:
define([
'jquery',
'underscore',
'backbone',
'view/search', // requests view/search.js
], function($, _, Backbone, SearchView){
var AppRouter = Backbone.Router.extend({
routes: {
"": "home"
}
});
var initialize = function(){
var app_router = new AppRouter;
app_router.on('route:home', function(){
var homeView = new SearchView();
homeView.render();
});
Backbone.history.start();
};
return {
initialize: initialize
};
});
和我的view/search.js
:
define([
'jquery',
'underscore',
'backbone',
'text!templates/search.html'
], function($, _, Backbone, searchTemplate){
// console.log($,_,Backbone);
var SearchView = Backbone.View.extend({
...
});
return SearchView;
});
当我取消注释上面的console.log时,_
和Backbone
都是undefined
,但$
不是。我错过了什么?我的所有lib文件都是最新版本。
答案 0 :(得分:12)
Backbone和Underscore不符合AMD标准。默认情况下,它们不提供与RequireJS兼容的接口。
在最新版本中,RequireJS provide a useful way to solve the problem:
你的main.js:
require.config({
shim: {
underscore: {
exports: '_'
},
backbone: {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
}
},
paths: {
jquery: 'lib/jquery-min',
underscore: 'lib/underscore-min',
backbone: 'lib/backbone-min',
templates: '../templates'
}
});
require([
'app'
], function(App){
App.initialize();
});
答案 1 :(得分:0)
要扩展BAK的答案,您还需要提供baseUrl:
require.config({
baseUrl: 'js',
...
});