I feel like I’m missing something really obvious here. Here is my model:
define([
'underscore',
'backbone'
], function(_, Backbone) {
var spamTermsModel = Backbone.Model.extend({});
return spamTermsModel;
});
Here is the collection that uses the model:
define([
'jquery',
'underscore',
'backbone',
'models/spamTermsModel'
],
function($, _, Backbone, spamTermsModel) {
var spamTermsCollection = Backbone.Collection.extend({
model: spamTermsModel,
url: 'spam-terms',
initialize: function(models, options) {
//console.log(models);
this.fetch({
success: function(data, options) {
//console.log(data); // logs data correctly
}
});
}
});
return spamTermsCollection;
}
);
Here is the view where I call the collection:
define([
'jquery',
'underscore',
'backbone',
'models/spamTermsModel',
'collections/spamTermsCollection'
], function($, _, Backbone, spamTermsModel, spamTermsCollection) {
var searchTermsView = Backbone.View.extend({
initialize: function() {
var stm = new spamTermsModel();
console.log(stm); // returns function()
this.collection = new spamTermsCollection();
console.log(this.collection.toJSON()); // returns empty collection
},
retrieveTemplate: function(model) {
return _.template($('#spamTermsTemplate').html(), model);
},
createList: function() {
var list = '';
_.each(this.collection.toJSON(), function (obj) {
list += obj.term + ', ';
//console.log(obj);
});
//console.log(this.collection.toJSON());
return list;
},
render: function() {
list = this.createList();
this.$el.html(this.retrieveTemplate(list));
return this;
}
});
return searchTermsView;
});
});
And finally my route:
router.on('route:updateSpamTerms', function() {
require(['views/spamTermsView'], function(st) {
s = new st();
$('#web-leads').html(s.render().el);
});
});
I think the problem is in my model, since it console.log()s function(). I feel like it should log a new model. I tried returning a new model, but I got an error that the model was not a constructor. What am I missing here?
this.collection = new spamTermsCollection();console.log(this.collection.toJSON()); // returns empty collection
This is because your fetch is asynchronous, and you are trying to access it before it is successfully fetched.
You can bind to the collection’s
resetevent and render your collection view then.this.collection.on('reset', this.render, this);This should work if the fetch is always asynchronous, but if for some reason it is not in the future, you might have problems. You could consider moving the fetch out of
initializeto make sure: