Backbonejs - 如何初始化视图?

时间:2017-06-21 00:01:49

标签: javascript backbone.js

不知何故,当我初始化我的视图时,我收到错误Uncaught TypeError: Cannot read property 'toJSON' of undefined

我有以下代码:

//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})

2 个答案:

答案 0 :(得分:1)

您的收藏是空的。因此this.model.at(this.model.currentTrack);实际上this.collection.at(0);将返回undefined。因此,您正在执行undefined.toJSON()

您需要在此处放置空值检查,并等待在呈现之前获取集合数据。

最好将集合作为collection而不是model传递

答案 1 :(得分:0)

我找到了答案!在渲染之前,我必须等待集合被提取为T J said

他说要用

this.fetch({success: function(){ this.render }})

this.fetch().then(function(){ this.render });

但最后我用

做了
this.fetch().done(function(){ this.render() });