How to represent arrays within ember-data models?

前端 未结 7 1135
不思量自难忘°
不思量自难忘° 2020-12-05 00:29

Is it necessary to use DS.hasMany pointing to a DS.Model when a model contains an array? Even if the array elements are not really models (no IDs o

相关标签:
7条回答
  • 2020-12-05 01:20

    Interestingly all the other 4 answers to this question have almost identical deserialize and serialize functions, so you could simplify things down to:

    import Em from 'ember'
    import DS from 'ember-data'
    
    # Presumably based on these answers: http://stackoverflow.com/questions/12168570/how-to-represent-arrays-within-ember-data-models
    # All we need to do is always make sure an array is returned from serialize or deserialize
    
    toArray = (data) ->
      switch Em.typeOf(data)
        when 'array'  then data
        when 'string' then JSON.parse(data)
        else []
    
    export default DS.Transform.extend
      deserialize: toArray
      serialize: toArray
    

    This is using ember-cli-coffees6 for coffeescript with import/export support

    0 讨论(0)
提交回复
热议问题