【问题标题】:rails backbone.js uncaught type errorrailsbone.js 未捕获的类型错误
【发布时间】:2015-04-28 19:59:55
【问题描述】:

在我的骨干应用程序内的追随者集合中,我有以下内容

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

令我困惑的是,在初始化对象中,options.user_id 中的 user_id 抛出错误

     Uncaught TypeError: Cannot read property 'user_id' of undefined

现在,这就是我想要它做的事情,即获取 user_id,以便我可以将其放入 api url,但会发生此错误,这反过来又不允许我推送到 heroku。

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

【问题讨论】:

    标签: javascript ruby-on-rails backbone.js heroku


    【解决方案1】:

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

    new Curate.Collections.Following();
    

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

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

    附: Backbone.Collectioninitialize 方法中的这一行是不必要的

    this.add(models);
    

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

    【讨论】:

    • 感谢您的建议,我的路线填写了新的集合声明,但我有一个不必要的 id: parseInt(id) 而不仅仅是 user_id: id
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-29
    • 2014-12-07
    • 2015-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多