Ember.js 余烬数据:如何将传入的空值设置为空字符串值?

Ember.js 余烬数据:如何将传入的空值设置为空字符串值?,ember.js,ember-data,Ember.js,Ember Data,我使用Ember数据(v1.13.13)来管理来自服务器的对象 传入属性的值为null。属性类型是默认值为空字符串的字符串。空值并不像预期的那样默认为空字符串。因此,看起来Ember数据在默认情况下建立了一个可为null的字符串数据类型(一般来说,考虑它,当然不是JavaScript) 在任何情况下,我都想知道在模型“实例化”时如何将传入的null转换为默认的空字符串值。用字符串类型而不是空字符串类型来表示或赋值数据的属性。 模型(简化): 传入对象: { "notes": [{

我使用Ember数据(v1.13.13)来管理来自服务器的对象

传入属性的值为null。属性类型是默认值为空字符串的字符串。空值并不像预期的那样默认为空字符串。因此,看起来Ember数据在默认情况下建立了一个可为null的字符串数据类型(一般来说,考虑它,当然不是JavaScript)

在任何情况下,我都想知道在模型“实例化”时如何将传入的null转换为默认的空字符串值。用字符串类型而不是空字符串类型来表示或赋值数据的属性。

模型(简化):

传入对象:

{
    "notes": [{
        "mystring": null
    }]
}
内存中的结果值:

<App.Note:ember1133:1775>
mystring: null

mystring:null

空字符串和空字符串是不同的,所以余烬数据的
字符串
转换不进行转换也就不足为奇了。但是,您可以编写自己的,它可以:

// transforms/string-null-to-empty.js
export default DS.Transform.extend({
  deserialize(serialized) { return serialized || ''; },
  serialize(deserialized) { return deserialized; }
});
然后


重写RESTSerializer中的
normalize
方法也可以实现这一目的。像这样的东西应该有用

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);
   }
 });
当然,如果您并不总是知道需要将哪些键从null规范化为空字符串,那么您可以对所有键进行迭代(不过这会更慢)


默认值通常用于新记录,而不是旧记录。处理空值,依我看,这是“事实”。你可能是对的。我使用默认值来设置传入项目的初始类型。当然,只要你编辑一个绑定的数字,它就会转换成一个字符串。需要尊重JavaScript变量的行为。在服务器端被占用的时间太长了。您应该调用
super
,并返回结果。@torazaburo哦,是的,当然,谢谢。那是我的愚蠢疏忽。
mystring: DS.attr('string-null-to-empty')
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);
   }
 });
DS.RESTSerializer.extend({
   normalize: function(modelClass, hash, prop) {
     Object.keys(hash).forEach(function(key){
       hash[key] = hash[key] || '';
     });
     return this._super(modelClass, hash, prop);
   }
 });