骨干错误无法调用方法'toJSON'?

时间:2013-09-15 22:28:40

标签: javascript backbone.js underscore.js

我想从我的收藏中渲染每个服务员,但是控制台仍然显示错误:

未捕获的TypeError:无法调用未定义的方法'toJSON'

这是我的代码:

 (function() {

    window.App = {

        Models: {},
        Views: {},
        Collections: {}

    };

    window.template = function(id) {

        return _.template( $('id' + id).html() );

    },

//等待模型

    App.Models.Waiter = Backbone.Model.extend({

        defaults: function() {
            return {
                title: 'Waiter Name',
                id: []
            };
        }
    });         

//等待收集的列表

   App.Collections.Waiters = Backbone.Collection.extend({

       model: App.Models.Waiter
   });

//查看所有等待者

   App.Views.Waiters = Backbone.View.extend({

       tagName: 'ul',

       render: function() {

           this.collection.each(function(waiter) {

               var waiterView = new App.Views.Waiter({ model: waiter });

               this.$el.append(waiterView.render().el);

           }, this);

           return this;
       }
   }); 

//一个人的视图

    App.Views.Waiter = Backbone.View.extend({

        tagName: 'li',

        template: _.template("<%= title %><%= id %>"),

        render: function() {

            this.$el.html( this.template(this.model.toJSON()) );

            return this;

        },
    });


       waitersCollection = new App.Collections.Waiters([
           {
               title: 'ferko fristansky',
               id: 2
           },
           {
               title: 'ferko bandaska',
               id: 3
           },
           {
               title: 'fvwerv fristansky',
               id: 4
           }    

       ]);

       var waitersView = new App.Views.Waiter({ collection: waitersCollection });

        $(document.body).append(waitersView.render().el);


})();

1 个答案:

答案 0 :(得分:1)

您正在使用集合创建waiterView

var waiterView = new App.Views.Waiter({ collection: waitersCollection });

App.Views.Waiter是基于模型的视图;这意味着this.model中的undefinedApp.Views.Waiter,因此会失败:

this.$el.html( this.template(this.model.toJSON()) );
// this is undefined -------------^^^^^

您可能想要创建一个App.Views.Waiters

var waitersView = new App.Views.Waiters({ collection: waitersCollection });

然后,在App.Views.Waiters内,您为集合中的每个模型创建一个App.Views.Waiter而不是new App.Views.extend({ model: waiter })

render: function() {
    this.collection.each(function(waiter) {
        var waiterView = new App.Views.Waiter({ model: waiter });
        this.$el.append(waiterView.render().el);
    }, this);
    return this;
}

顺便说一句,请小心:

App.Models.Waiter = Backbone.Model.extend({
    defaults: {
        title: 'Waiter Name',
        id: []
    }
});

来自defaults的值被浅层复制,因此使用这些默认值的所有内容最终将使用完全相同的id数组,当您有多个模型共享相同的id数组时,这会导致奇怪的错误1}}数组。如果defaults中有可变值,则通常需要使用函数,以便每个人都获得自己的不同值:

App.Models.Waiter = Backbone.Model.extend({
    defaults: function() {
        return {
            title: 'Waiter Name',
            id: []
        };
    }
});