I’m following an example on how to use require.js and backbone.js. In the example, the model does not use new when it returns. In my code I have to use new otherwise I get an error:
Uncaught TypeError: Object function (){a.apply(this,arguments)} has no method 'toJSON'
Doesn’t work:
define([
'underscore',
'backbone'
], function(_, Backbone) {
var personModel = Backbone.Model.extend({
defaults: {
conversations: 'No Conversations'
},
initialize: function(){
}
});
return personModel;
});
Works:
define([
'underscore',
'backbone'
], function(_, Backbone) {
var personModel = Backbone.Model.extend({
defaults: {
conversations: 'No Conversations'
},
initialize: function(){
}
});
return new personModel;
});
Anybody know why?
Backbone.Model.extendreturns a constructor function–not an actual object. The constructor isn’t an object (and consequently won’t have any properties) until it’s been instantiated usingnew(as in your second example). That means thattoJSONisn’t available, either, and you end up with the error you’re seeing.When you’re ready to actually create a new
personModel, you might do it something like this (I’ll assume that the module you described above has been defined as “Person”):