Whenever I try to initialize my view, I encounter an error message
Uncaught TypeError: Cannot read property 'toJSON' of undefined
Here is the code snippet causing the issue:
//Model
var Song = Backbone.Model.extend({
defaults: {
title: 'Red',
artist: 'Taylor Swift',
filename: 'audio1.mp3',
playlist: 0
},
});
//Collection
var Playlist = Backbone.Collection.extend({
model: Song,
localStorage: new Backbone.LocalStorage('playlist'),
initialize: function(models,options) {
_.extend(this,_.pick(options, 'currentTrack'));
this.fetch({ajaxSync: true})
},
url: 'metadata',
parse: function(response){
return response
},
currentTrack: 0,
currentTime: 0
});
//View
var Player = Backbone.View.extend({
tagName: "audio",
id: "player",
model: playlist,
currentSong: function(){
console.log(this.model);
return this.model.at(this.model.currentTrack).toJSON();
},
events: {
'ended': 'next',
'pause': 'saveTime'
},
newTemplate: _.template('<source src="<%= filename %>" >'),
initialize: function(){
this.render();
},
render: function(){
this.$el.html(this.newTemplate(this.currentSong()));
$(document.body).html(this.el);
},
next: function(){
if(this.model.length == this.model.currentTrack){
console.log('End of the playlist');
}
else{
this.model.currentTrack++;
console.log('currentTrack: ', this.model.currentTrack);
this.render();
this.el.src = this.currentSong().filename;
this.el.play();
}
},
saveTime: function(){
console.log('Saving currentTime:', this.el.currentTime);
this.model.currentTime = this.el.currentTime;
}
});
var playlist = new Playlist();
var player = new Player({model: playlist});
It appears that upon initializing the player
view, the playlist
collection is not populated. Interestingly, running
var player = new Player({model: playlist})
directly from the console works fine.