主干视图集合错误

Backbone view collection error

本文关键字:错误 集合 视图      更新时间:2024-02-06

我是主干网的新手,只是想让这个视图发挥作用。我想从用户填写的表单中提供集合数据,然后将用户重定向到其他地方。然而,我不断得到一个未定义的错误,即:

 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对象正确设置了点击事件。它应该如你所期望的那样工作。你输入的代码一点问题都没有。由于如果通过主干events 设置事件,this总是引用View实例

因此,只有两个可能的原因会导致错误。

  1. this没有引用View实例。这意味着您显式地更改了this引用的内容,或者使用了类似$(this.el).on("click")的内容,因为这将this引用的内容更改为单击的元素。

  2. 调用initialize后,this.collection以某种方式被覆盖。你有可能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
     },