我正在重写一个 Backbone.js 应用程序,尝试使用 AMD 方法。我已经下载了 AMD 化版本的 Backbone 和 Underscore。我检查了一下,jQuery、Backbone 和 Underscore 都被调用了。这是一个相当简单的项目,但出于某种原因,我的收藏不再传递到我的 View 中。我是 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;
});
这里是 View 和集合实例化的地方:
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);
});
为什么我在 console.log(tablesCollection)
时返回了 function (){return c.apply(this,arguments)}
?就像没有传入集合一样。这可能是路径问题吗?我的项目由一个 js
文件夹构成,该文件夹包含名为 collections
、models
和 views
的子文件夹。如果我 console.log(this)
,我得到:
我的数据在那里,但这是我需要的吗?为什么当我尝试 console.log
时我得不到我的收藏?
最佳答案
不要直接使用tablesCollection
。使用 this.collection
。您已经用它初始化了 View
关于backbone.js - 主干 : Collection not being passed into view with Require. js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14589101/