Ember中的对象关系,不使用Ember-Data

时间:2017-06-06 21:14:55

标签: ember.js ember-cli

我们在项目中不使用Ember-Data。我们得到了一个场景,其中每个模型都具有另一个类型模型的id。事实上,我们也没有模特。我们使用普通的Ajax。

让我们选择2个模型测试和应用。测试将包含为其创建测试的应用程序ID。当我检索测试时,我也想要应用程序数据。当我们使用关系时,Ember-Data默认执行此操作。如果没有Ember-Data,我怎样才能做到这一点。可能有2个相同应用程序的测试。检索完应用程序数据后,我不想再针对相同的应用程序数据发出请求。

1 个答案:

答案 0 :(得分:0)

我的回答 - 创建您自己的内存存储(服务看起来像Ember-way解决方案),用于存储已加载的记录。例如,它可能具有如下结构:

// app/services/store.js

export default Ember.Service.extend({
    ajax: Ember.inject.service(),

    store: {
        applications: [],
        tests: []
    },

    getTest(id) {
        const store = this.get('store');

        return new Ember.RSVP.Promise(resolve => {
            const loadedTest = store.tests.findBy('id', id);
            if (loadedTest) {
                return resolve(loadedTest);
            }

            this.get('ajax').getRequest(urlForGettingTestWithConcreteId).then(test => {
                if (test.application) {
                    const application = store.applications.findBy('id', test.application);

                    if (application) {
                        test.application = application;

                        store.tests.pushObject(test);

                        return resolve(test);
                    }

                    this.get('ajax').getRequest(test.application).then(application => {
                        test.application = application;

                        store.applications.pushObject(application);                        
                        store.tests.pushObject(test);

                        resolve(test);
                    });
                }
            });
        });
    }
});

它应该有效的混合伪代码和代码,但您应该很容易使用它来处理您的应用程序。 :)

相关问题