MartinElvar
MartinElvar

Reputation: 5804

Backbone is not firing request on save

I got this very simple Guest model

define([
], function() {
  Guest = Backbone.Model.extend({

    urlRoot : ftd.settings.rest + '/guest',

    defaults: {
      id : '',
      name : '',
      accessToken : ''
    },

    validate: function( attr ) {
      var errors = [];
      if(attr.name.length < 4) {
        errors.push({message : "You nickname, must be atleast 4 chars", name : 'guestNickname'});
      }
      return errors;
    }
  });

  return Guest;
});

Then i got a frontpage view, where guest signs up, basicly this happens when the submit button is clicked.

createGuest: function( ev ) {
  ev.preventDefault();
  // Get nickname.
  var guest = new Guest();
  guest.bind( 'error', function( model, errors ) {
        _.each( errors, function( err ) {
      $('input[name=' + err.name + ']').addClass('invalid');
      // add a meesage somewhere, using err.message
          }, this );
  });

  guest.save({
    'name' : $('input[name="guestNickname"]').val()
  }, {
    wait:true,
    success:function(model, response) {
      console.log('Successfully saved!');
    },
    error: function(model, error) {
      console.log(error);
    }
  });
},

So i take the name from my input element, and i put it into the save method. The problem is, that Backbone doesn't send a request to the server, is simply just triggers the error event. Which print a empty error array. What am i doing wrong?

Upvotes: 1

Views: 188

Answers (1)

Paul Hoenecke
Paul Hoenecke

Reputation: 5060

You are supposed to not return anything if the validation succeeds.

Since you are returning an empty array, it assumes that array is the validation error.

Try this:

validate: function( attrs ) {
      var errors = [];
      if(attrs.name.length < 4) {
        errors.push({message : "You nickname, must be atleast 4 chars", name : 'guestNickname'});
      }
      if(errors.length > 0){
          return errors;
      }
    }

Upvotes: 1

Related Questions