问题
I am using Ember-Data (v1.13.13) to manage objects coming from the server.
The value of an incoming attribute is null. The attribute type is a string with default value being an empty string. The null is not defaulting to the empty string as expected. So it looks like Ember-Data establishes a nullable string data type by default (thinking about it in general terms, not a JavaScript thing, of course).
In any case, I would like to know how to convert the incoming null to the default empty string value as the model is "instantiated". That or indicate to Ember-Data to consider the property in terms of a string type rather than a nullable string type.
The model (simplified):
App.Note = DS.Model.extend({
mystring: DS.attr('string', { defaultValue: '' })
});
The incoming object:
{
"notes": [{
"mystring": null
}]
}
The resulting value in memory:
<App.Note:ember1133:1775>
mystring: null
回答1:
Null and empty string are different, so it is not surprising that Ember Data's string
transform does not do that conversion. However, you can write your own which does:
// transforms/string-null-to-empty.js
export default DS.Transform.extend({
deserialize(serialized) { return serialized || ''; },
serialize(deserialized) { return deserialized; }
});
then
mystring: DS.attr('string-null-to-empty')
回答2:
Overriding the normalize
method in your RESTSerializer will also do the trick. Something like this should work
DS.RESTSerializer.extend({
normalize: function(modelClass, hash, prop) {
// Do whatever checking you need to to make sure
// modelClass (or hash.type) is the type you're looking for
hash.mystring = hash.mystring || '';
return this._super(modelClass, hash, prop);
}
});
Of course, if you don't always know which keys you'll need to normalize from null to an empty string then you could just iterate over all of them (however this will be slower).
DS.RESTSerializer.extend({
normalize: function(modelClass, hash, prop) {
Object.keys(hash).forEach(function(key){
hash[key] = hash[key] || '';
});
return this._super(modelClass, hash, prop);
}
});
来源:https://stackoverflow.com/questions/33015484/ember-data-how-do-i-set-an-incoming-null-value-to-an-empty-string-value