Reputation: 1719
I'm writing a small app using Backbone. I start creating a SongsView which creates a SongsCollection. I fetch this collection to retrieve the data from an external API I wrote. The next step is to render the fetched data using the toJSON
method, however calling toJSON
returns [undefined]
, despite the fact that the collection is an instance of Bakcbone.Collection.
Here is my code (in coffeescript):
App:
songs = new SongsView
songs.render()
SongsView:
SongsCollection = require 'scripts/collections/songs'
class SongsView extends Backbone.View
el: '#songs'
render: ->
songs = new SongsCollection
songs.fetch
success: ( res ) =>
console.log (res instanceof Backbone.Collection) # true
console.log (res instanceof SongsCollection) # true
console.log (res.toJSON()) # [undefined]
SongsCollection:
Song = require 'scripts/models/song'
class SongsCollection extends Backbone.Collection
model: Song
url: 'http://localhost:1337/songs'
Song:
class Song extends Backbone.Model
constructor: ({@name, @path}) ->
console.log 'new'
EDIT: If I look at the prototypes chain, I can find a toJSON() method though :
EDIT²: Same behavior for a single model :
console.log (res.models[0].toJSON()) # undefined
Which is actually interesting. It means that the toJSON
method from the SongsCollection works but the toJSON
from Song
does not. I'll dig deeper there.
Upvotes: 0
Views: 412
Reputation: 1719
Problem solved. I was using constructor
instead of initialize
which leads to create a model without any attributes
, thus, calling toJSON returned undefined
as the attributes
property was not defined.
class Song extends Backbone.Model
initialize: ({@name, @path}) ->
console.log 'new'
Upvotes: 1