require()
时会产生一个空对象。我的文件结构如下: src
|__ public
|__ javascript
|__ collections
| categories.js
| listings.js <-- Always an empty object
|__ models
| category.js
| employer.js
| listing.js
| location.js
| routing
| templates
| tests
| ui-components
| views
问题文件是 collections/listings.js
,当像这样需要时,它似乎只输出一个空对象:
var ListingsCollection = require('../collections/listings')
src/public/javascript/collections/listings.js
看起来像这样:var $ = require('jquery'),
_ = require('underscore'),
Backbone = require('backbone'),
Listing = require('../models/listing');
Backbone.$ = $;
module.exports = Backbone.Collection.extend({
url: '/listings',
model: Listing,
parse: function (response) {
return response.listings;
}
});
以下是一个出现问题的示例:
var $ = require('jquery'),
_ = require('underscore'),
Backbone = require('backbone'),
LocationModel = require('../models/location'),
ListingsCollection = require('../collections/listings');
Backbone.$ = $;
console.log(ListingsCollection); // > Object {}
module.exports = Backbone.Model.extend({
urlRoot: '/employers',
model: {
location: LocationModel,
listings: ListingsCollection
},
parse: function (response) {
var employer = response.employer;
// Create the child listings
employer.listings = new ListingsCollection;
return employer;
},
toJSON : function () {
var json = _.clone(this.attributes);
_.each(_.keys(this.model), function (child) {
if (this.get(child)) {
json[child] = this.get(child).toJSON();
}
}.bind(this));
return json;
}
});
所以,问题就在这里——该集合从未被要求进入雇主模型,因此它可以用来为父模型创建一个子集合。我已经查看了源代码并研究了这个问题,但目前还没有找到任何解决办法…… 这很令人困惑。