I have this code which, for reasons I can't understand, produces an empty object when using require()
. My file structure is like this:
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
The problem file is collections/listings.js
, which seems to simply output as an empty object when required like so:
var ListingsCollection = require('../collections/listings')
src/public/javascript/collections/listings.js
looks like this:
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;
}
});
Here is an example of where things go wrong:
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;
}
});
So there it is - That collection never requires into the employer model such that it can be used to create a child collection for the parent model. I've looked at the source and researched this issue but I'm coming up with nothing so far... It's perplexing.