Backbone 查看 collection 错误

Backbone view collection error

我是 backbone 的新手,我只是想让这个视图发挥作用。我想从用户填写的表单中提供 collection 数据,随后会将用户重定向到其他地方。但是,我不断收到未定义的错误,即:

 Uncaught TypeError: undefined is not a function 

这是导致错误的代码:

 //this lives within a Backbone view, as does the following constructor.
 clickSubmitRegister: function(e) {
     e.preventDefault();
     var formData = {};
     $('#registrationForm').find('input').each(function() {
         value = $(this).val();
         thisId = $(this).attr('id');
         if (value != '') {
             formData[thisId] = value;
         }
     });
     console.log(formData); //this displays the correct data, all good
     this.collection.create(formData); //this line throws me the error
 },

初始化构造函数如下:

initialize: function() {
    this.collection = new app.User();
    this.render();
},

如果您通过 this.events 正确设置了点击事件,object.It 应该可以正常工作,因为您输入的 expected.and 代码完全没有问题。 因为如果您通过 backbone events

设置事件,this 总是引用 View 实例

所以您收到错误的可能原因只有 2 个。

  1. this 未引用视图 instance.which 表示您更改了 this 明确引用的内容,或者您​​使用了类似 $(this.el).on("click") 的内容,因为这将 this 指的内容更改为单击的元素。

  2. this.collection 在 initialize 被调用后以某种方式被覆盖。 ofc 你有可能 this.collection.create 也被替换了。

我们无法同时检查它们,因为您没有提供完整的代码。

所以尝试

     //this lives within a Backbone view, as does the following constructor.
     clickSubmitRegister: function(e) {
         e.preventDefault();
         var formData = {};
         $('#registrationForm').find('input').each(function() {
             value = $(this).val();
             thisId = $(this).attr('id');
             if (value != '') {
                 formData[thisId] = value;
             }
         });
         console.log(formData); //this displays the correct data, all good
         console.log(this); //to check which object 'this' refers
         console.log(this.collection); //to check if this.collection got replaced or not
     },