我正在重写一个试图使用 AMD 方法的 Backbone.js 应用程序。我已经下载了 AMD 版本的 Backbone 和 Underscore。我检查并调用了 jQuery、Backbone 和 Underscore。这是一个相当简单的项目,但由于某种原因,我的收藏不再传递给我的视图。我是 AMD 的新手。
这是我的模型:
define([
'underscore',
'backbone'
], function(_, Backbone) {
var tableModel = Backbone.Model.extend({});
return tableModel;
});
这是我的收藏:
define([
'jquery',
'underscore',
'backbone',
'models/tableModel'
],
function($, _, Backbone, tableModel) {
var tablesCollection = Backbone.Collection.extend({
url: this.url, // passed into collection at runtime, so same code can process multiple sets of data
model: tableModel,
initialize: function(models, options) {
if (options && options.url) {
this.url = options.url;
}
this.fetch({
success: function(data, options) {
if ($.isEmptyObject(data.models)) {
App.Collections.Tables.NoData(data);
}
}
});
}
});
return tablesCollection;
});
这是我的看法:
define([
'jquery',
'underscore',
'backbone',
'models/tableModel',
'collections/tablesCollection',
'views/tableView'
],
function($, _, Backbone, tableModel, tablesCollection, tableView) {
var tv = Backbone.View.extend({
tagName: 'div',
initialize: function() {
console.log(this.collection); // returns collection and undefined
this.collection.on('reset', this.render, this); // errors: this.collection is undefined
},
render: function() {
return this;
}
});
return tv;
});
这里是视图和集合被实例化的地方:
define([
'jquery',
'underscore',
'backbone',
'models/tableModel',
'collections/tablesCollection',
'views/tablesView'
], function($, _, Backbone, tableModel, tablesCollection, tablesView) {
var t = new tablesCollection(null, { url: 'main-contact'} );
var tables = new tablesView({ collection: t, template: 'main-contact-template'});
$('#web-leads').html(tables.render().el);
});
为什么我会被function (){return c.apply(this,arguments)}
退回console.log(tablesCollection)
?就像集合没有被传入一样。这可能是路径问题吗?我的项目由一个js
文件夹构成,其中包含名为collections
和models
的子文件夹views
。如果我console.log(this)
,我得到:
我的数据在那里,但这是我需要的吗?为什么我尝试收藏时没有得到我的收藏console.log
?