问题
I am getting an error in an Ember Transformer trying a parse a date in the serialize function.
Error message:
"Attempted to handle event didCommit
on <(subclass of DS.Model):ember1597:8260357> while in state root.loaded.updated.uncommitted."
Strangely enough, the data is transmitted correctly parsed to the server.
Code:
DS.Transform.extend({
deserialize : function(serialized) {
var array = [];
if (Ember.isArray(serialized)) {
serialized.forEach(function(item) {
if (item.feldTyp === "DATE_FIELD" && item.value) {
Ember.set(item, "value", moment(item.value, "DD.MM.YYYY"));
}
array.addObject(Ember.Object.create(item));
});
}
return array;
},
serialize : function(deserialized) {
if (Ember.isArray(deserialized)) {
deserialized.forEach(function(item) {
if (item.get('feldTyp') === "DATE_FIELD" && item.get('value')) {
item.set('value', moment(item.get('value')).format("DD.MM.YYYY"));
}
});
return deserialized;
}
return [];
}
});
The line item.set('value', moment(item.get('value')).format("DD.MM.YYYY"));
causes the error as commented out the error vanishes. I tried other things like setting a static value or setting the value using Ember.set
but without success. I do not quite know what went wrong here and thus cannot think of a solution. Can someone help? Thanks in advance.
edit
Workaround: I moved the serialization into the controller. Does not look as elegant but works for now...
回答1:
As you've figured out ember data doesn't like the use of set
in its transforms. Because the server representation of data is often different from how it is represented on the client side. Ember expects transforms to not modify the serialized
or deserialized
values that are passed in and instead to return new values.
The reason this error is happening is because ember has a state machine to track the state of a record in relation to the server (see http://emberjs.com/api/data/classes/DS.RootState.html). In this case ember is most likely putting the record into the inFlight
state. It then calls the transform's serialize function. When item.set
is called ember notices a change to the record and inadvertently transitions the record back into the uncommitted
state. After the server responds to the save request ember mistakenly assuming the record is still in the inFlight
state signals the didCommit
event so the record can transition to the saved
state. Because the uncommitted
state doesn't support the didCommit
event ember throws an error.
I suspect you could fix this issue by rewriting your serialize function to not call set
and instead to return a new array.
serialize : function(deserialized) {
if (Ember.isArray(deserialized)) {
return deserialized.map(function(item) {
if (item.get('feldTyp') === "DATE_FIELD" && item.get('value')) {
return moment(item.get('value')).format("DD.MM.YYYY");
}
});
}
return [];
}
来源:https://stackoverflow.com/questions/21697991/ember-js-error-while-parsing-data-in-transformer-handeling-event-didcommit-in