不知怎的,當我初始化我的看法,我得到一個錯誤Uncaught TypeError: Cannot read property 'toJSON' of undefined
Backbonejs - 我如何初始化視圖?
我有以下代碼:
//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});
不知怎的,當我初始化player
查看playlist
colleciton尚未填充呢。我可以從控制檯運行var player = new Player({model: playlist})
。
您很可能需要監聽收集事件並渲染視圖。如果你調試,什麼變量是未定義的?另外,'playlist'是一個集合,所以它應該是'collection:playlist' – vassiliskrikonis
這是this.model返回undefined – medicengonzo
'model:playlist,'在視圖屬性中(在'extend'中)沒用。這是一個應該在實例化時傳遞的選項,就像你在底部一樣。 –