Backbone Uncaught TypeError:无法调用方法' toJSON'未定义无法获取模型

时间:2013-08-14 16:04:14

标签: ruby-on-rails backbone.js

我正在尝试使用Backbone在rails中构建应用程序。我正面临一个问题,我在模型上得到一个未定义,我尝试阅读它。

这是我的代码。

//集合

Quizzer.Collections.Posts = Backbone.Collection.extend({

   model: Quizzer.Models.Post,
   url: "/posts"

});

//型号

Quizzer.Models.Post = Backbone.Model.extend({

});

// PostIndex视图

Quizzer.Views.PostsIndex = Backbone.View.extend({

    template: JST['posts/index'],
    el: '#posts',

    render: function(){
        $(this.el).html(this.template);
        $(this.projectsCallView());
        return this;
    },

    projectsCallView: function(){
        var pp = new Quizzer.Views.Posts({ collection : new Quizzer.Collections.Posts });
        this.$("ul").append(pp.render().el)
    }

});

//帖子视图

Quizzer.Views.Posts = Backbone.View.extend({
    el: '#container',

    template: JST['posts/posts'],

    initialize: function(){
        this.listenTo(this.collection, 'reset', this.render);   
        this.collection.fetch({ reset:true });
        },

    render:function(){
        $(this.el).html(this.template());
        _.each(this.collection,this.addOne);
        return this;
    },

    addOne: function(model){
        console.log(model);
        var vv = new Quizzer.Views.PostW({ model: model })
        $("ul").append(vv.render().el)
    }

});

// PostW View

Quizzer.Views.PostW = Backbone.View.extend({
    template: JST['posts/postsw'],

    render: function() {
        console.log(this.model)
        $(this.el).html(this.template(this.model.toJSON()));
        return this;
    }
});

你能告诉我问题在哪里吗?

1 个答案:

答案 0 :(得分:1)

而不是

_.each(this.collection,this.addOne);

DO

this.collection.each(this.addOne);