How to create nested models in Ember.js?

前端 未结 4 1457
感情败类
感情败类 2020-12-24 09:16

Going through Ember.js documentation, I am not able to figure out how to create nested models. Assume that I have the following JSON:

App.jsonObject = {
             


        
4条回答
  •  忘掉有多难
    2020-12-24 09:35

    I wrote my own simple model factory based on Alexandros K's solution but supporting ES6 modules. Thought I would share it :)

    import Ember from 'ember';
    
    var ModelFactory = Ember.Object.extend({});
    
    ModelFactory.reopenClass({
        getType(obj) {
            if(!obj) {
                return null;
            }
    
            if(Array === obj.constructor) {
                return "array";
            }
            else if(typeof obj === "object") {
                return "object";
            }
    
            return null;
        },
    
        // Factory method..
        create: function (arg) {
    
            const _this = this;
    
            switch (this.getType(arg)) {
    
                // Return an Ember Array
                case "array":
    
                    var newArray = [];
    
                    arg.forEach(function(item) {
                        newArray.pushObject(_this.create(item));
                    });
    
                    return newArray;
    
                // Or a recursive object.
                case "object":
    
                    var newObject = Ember.Object.create();
    
                    for (var key in arg) {
                        if (arg.hasOwnProperty(key)) {
                            newObject.set(key, this.create(arg[key]));
                        }
                    }
    
                    return newObject;
    
                default:
    
                    // Or just return the args.
                    return arg;
            }
        }
    });
    
    
    export default ModelFactory;
    

    Usage:

    ModelFactory.create(json)
    

提交回复
热议问题