I’m trying to figure out the right way to declare a model for a Backbone Collection in CoffeeScript. Let me demonstrate with an example:
class MyApp.Collections.Likes extends Backbone.Collection
constructor: (@models, @options) ->
model: MyApp.Models.Like
When I initialize this collection and create a new model, it fails.
likes = new MyApp.Collections.Likes
like = new likes.model // same result for likes.model.new
TypeError: Result of expression 'likes.model' [undefined] is not an object.
Looking at the compiled JavaScript, the model is defined as follows:
MyApp.Collections.Likes = (function() {
__extends(Likes, Backbone.Collection);
function Likes(models, options) {
this.models = models;
this.options = options;
}
Likes.prototype.model = MyApp.Models.Like; // <--
return Likes;
})();
I could define the model in two ways that will work:
Solution 1
class MyApp.Collections.Likes extends Backbone.Collection
constructor: (@models, @options) ->
model: -> MyApp.Models.Like // Notice the ->
Which compiles it to:
MyApp.Collections.Likes = (function() {
__extends(Likes, Backbone.Collection);
function Likes(models, options) {
this.models = models;
this.options = options;
}
Likes.prototype.model = function() { // <-- added to the prototype as a function
return MyApp.Models.Like;
}
return Likes;
})();
Solution 2
class MyApp.Collections.Likes extends Backbone.Collection
constructor: (@models, @options) ->
@model: MyApp.Models.Like // Notice the @
Which compiles it to:
MyApp.Collections.Likes = (function() {
__extends(Likes, Backbone.Collection);
function Likes(models, options) {
this.models = models;
this.options = options;
}
Likes.model = function() { // <-- not added to prototype
return MyApp.Models.Like;
}
return Likes;
})();
I’m pretty sure Solution 1 is the better solution. However, lots of sites I’ve looked at with tutorials define it without the -> or @.
Am I doing something blatantly wrong?
There isn’t anything wrong with the Like model, it’s pretty vanilla:
class MyApp.Models.Like extends Backbone.Model
I’m unable to replicate your error. Here’s my code:
Is it possible that you made a typo somewhere? In particular, is
MyApp.Models.Likedefined at the point where you writemodel: MyApp.Models.Like? The testsand
should both give you
true. And if they do, thennew likes.modelshould be equivalent tonew MyApp.Models.Like.