0

My Email object (my own custom class) is being written though the relation is not being set on time, any ideas how to chain this properly?

// Create new Email model and friend it
addFriendOnEnter: function(e) {
  var self = this;
  if (e.keyCode != 13) return;

  var email = this.emails.create({
    email:   this.emailInput.val(),
    ACL:     new Parse.ACL(Parse.User.current())
  });

  var user = Parse.User.current();
  var relation = user.relation("friend");
  relation.add(email);
  user.save();

  this.emailInput.val('');
}

Thanks! Gon

2 Answers 2

2

Because talking to Parse's servers is asynchronous, Parse.Collection.create uses a Backbone-style options object with a callback for when the object is created. I think what you want to do is:

// Create new Email model and friend it
addFriendOnEnter: function(e) {
  var self = this;
  if (e.keyCode != 13) return;

  this.emails.create({
    email:   this.emailInput.val(),
    ACL:     new Parse.ACL(Parse.User.current())
  }, {
    success: function(email) {
      var user = Parse.User.current();
      var relation = user.relation("friend");
      relation.add(email);
      user.save();

      self.emailInput.val('');
    }
  });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @bklimt! New to Backbone indeed, sounds like 'success' is always an [option] :) Sweet!
0

Got it!

The .create method on the this.emails collection does not actually return an object, so var email was empty. Somehow Parse guess it was an empty object of class Email, so I guess the structure is the only thing that remained once .create did its job.

Instead I retrieve the email object on the server using .query, .equalTo and .first

// Create new Email model and friend it
addFriendOnEnter: function(e) {
  var self = this;
  if (e.keyCode != 13) return;

  this.emails.create({
    email:   this.emailInput.val(),
    ACL:     new Parse.ACL(Parse.User.current())
  });

  var query = new Parse.Query(Email);
  query.equalTo("email", this.emailInput.val());
  query.first({
    success: function(result) {
      alert("Successfully retrieved an email.");
      var user = Parse.User.current();
      var relation = user.relation("friend");
      relation.add(result);
      user.save();
    },
    error: function(error) {
      alert("Error: " + error.code + " " + error.message);
    }
  });

  this.emailInput.val('');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.