Gon Zifroni
Gon Zifroni

Reputation: 213

Setting a Parse.Object.relation at/after object creation

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

Upvotes: 0

Views: 1585

Answers (2)

bklimt
bklimt

Reputation: 1842

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('');
    }
  });
}

Upvotes: 2

Gon Zifroni
Gon Zifroni

Reputation: 213

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('');
}

Upvotes: 0

Related Questions