简体   繁体   中英

Backbone view collection error

I'm new to backbone and am just trying to get this view to work. I want to feed a collection data from a form that a user fills out, which will subsequently redirect the user somewhere else. However, I keep getting an undefined error, namely:

 Uncaught TypeError: undefined is not a function 

Here is the code that causes the error:

 //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
 },

The initialize constructor is as follows:

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

If you properly set the click event via this.events object.It should work as you expected.and code you put has no problem at all. Since this always refer to View instance if you set the event via backbone events

So there are only 2 possible reason you get the error.

  1. this doesn't refer to the View instance.which means you changed what this refers explicitly or you used something like $(this.el).on("click") because this changes what this refers into clicked element.

  2. this.collection got override somehow after initialize is called. ofc You have a possibility that this.collection.create 's replaced too.

we can't check both of them since you haven't put the full code.

So try

     //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
     },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM