Reputation: 2323
I want to have a function return the promise from model.save()
, but the call to model.save()
is in a callback, and so doesn't make it up the chain. Here's what I mean:
function saveOn (target, attribute) {
target.addObserver(attribute, function () {
if (target.get(attribute)) {
target.removeObserver(attribute);
Ember.run.once(target, function() {
target.save();
});
}
});
};
(this function was necessary to solve this problem I previously posted)
I want the target.save();
line to instead be: return target.save();
Then I could do this:
saveOn().then();
which as it stands doesn't work, the error message simply being that then
doesn't exist on that object.
teacherSignUp: function() {
var model = this.get('model');
var teacher = this.get('store').createRecord('teacher', {
description: 'Why hello sir',
user: model
});
model.set('teacher', teacher);
saveOn(teacher, 'user.isFulfilled').then(function() {
console.log("Model");
saveOn(model, 'teacher.isFulfilled');
});
}
The console.log("Model");
is successfully called, but the model is never persisted at all.
What's happening here?
It the second observer on the model was never firing, since after the teacher had completed saveOn
the model was already done. I just changed the saveOn(model, 'teacher.isFulfilled');
to model.save();
and it works great.
Upvotes: 0
Views: 949
Reputation: 47367
pass another parameter.
function saveOn (target, attribute, then) {
target.addObserver(attribute, function () {
if (target.get(attribute)) {
target.removeObserver(attribute);
Ember.run.once(target, function() {
var promise = target.save();
if(then){
promise.then(function(){ then(); });
});
}
});
};
or create another promise and resolve in the then
function saveOn (target, attribute) {
return new Ember.RSVP.Promise(function(resolve, reject){
target.addObserver(attribute, function () {
if (target.get(attribute)) {
target.removeObserver(attribute);
Ember.run.once(target, function() {
target.save().then(function(record){ resolve(record); },
function(error){ reject(error); });
});
}
});
});
};
teacher.isFulfilled is probably already changed, so the observer isn't firing, cause it isn't changing, try checking before creating the observer and skipping that portion if already true/exists etc.
Upvotes: 1