rails backbone.js 未捕获类型错误

rails backbone.js uncaught type error

在我的 backbone 应用程序中的关注者 collection 中,我有以下内容

    window.Curate.Collections.Following = Backbone.Collection.extend({
        model: Curate.Models.User,

      initialize: function (models, options) {
        this.add(models);
        this.user_id = options.user_id;
      },

      url: function () {
        return '/api/users/' + this.user_id + '/following';
      },

      parse: function(response){
            this.page_number = parseInt(response.page_number);
        this.total_pages = parseInt(response.total_pages);
            return response.users;
      }
    });

    window.Curate.Collections.following = new Curate.Collections.Following();
    Curate.Collections.following.fetch({
      data: { page: 1 }
    });

让我感到困惑的是,在初始化 object 中 options.user_id 中的 user_id 抛出错误

     Uncaught TypeError: Cannot read property 'user_id' of undefined

现在它完成了我想要它做的事情,即获取 user_id,这样我就可以将它放入 api url 但是这个错误发生在 return 不允许我推送到 heroku。

知道这里发生了什么吗?谢谢

问题是您没有向您的集合传递任何参数,实际上您没有传递任何 options 对象

new Curate.Collections.Following();

它应该是这样的,包括 options 对象和 user_id

new Curate.Collections.Following([{}, {}], { user_id: 123 });

P.S。 Backbone.Collectioninitialize 方法中的这一行是不必要的

this.add(models);

因为 Backbone 在初始化后自动重置 constructor 中传入模型数组的集合。