How to represent arrays within ember-data models?

前端 未结 7 1133
不思量自难忘°
不思量自难忘° 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:12

    Well... It was a little bit difficult but mixing all answers in this post I made it work.

    Firstly, you should create a transform for the new type "array":

    DS.ArrayTransform = DS.Transform.extend({
      deserialize: function(serialized) {
        return (Ember.typeOf(serialized) == "array")
            ? serialized 
            : [];
      },
    
      serialize: function(deserialized) {
        var type = Ember.typeOf(deserialized);
        if (type == 'array') {
            return deserialized
        } else if (type == 'string') {
            return deserialized.split(',').map(function(item) {
                return jQuery.trim(item);
            });
        } else {
            return [];
        }
      }
    });
    
    App.register("transform:array", DS.ArrayTransform);
    

    Now, in your model, just use it as another attr:

    App.myModel = Ember.Model.extend({
        name : DS.attr('string'),
        cont : DS.attr('array')
    }
    

    And we are done. Remember, when adding elements to the array, to use pushObject.

    In a controller:

    this.get('model.cont').pushObject('new Item');
    

    I hope this helps someone.

提交回复
热议问题