mercredi 12 août 2015

Can I set an ember data model as a service?

I'm trying to set an ember data model as a service.

Until now I use one big initializer to do that but want to split it for the separation of concerns.

The first initializer should deferReadiness until an important library emmits a ready event and advanceReadiness can be called

The second initializer should query the store for a model instance and inject it into each controller and route. (basically a user's settings)

Because my adapters rely on the readiness of the library it's mandatory that the first initializer is finished before the second one starts. As far as I know initializers can't be chained in an async way, right? That's why I tried to use the beforeModel hook in the application route instead to get the model and replace a stubed service like this:

// app/routes/application.js

import Ember from 'ember';
const service = Ember.inject.service;

export default Ember.Route.extend({
    preferences: service(),

    beforeModel() {
        this.store.findAll('settings').then((records) => {
            let record = records.get('firstObject');
            this.set('preferences', record);
        });
    }
});

// app/initializer/preferences.js

export function initialize(container, application) {
    application.register('service:preferences', {}, { instantiate: false, singleton: true });

    application.inject('route', 'preferences', 'service:preferences');
    application.inject('controller', 'preferences', 'service:preferences');
}

export default {
    name: 'settings',
    initialize: initialize
};

I' trying it like this cause i read somewhere that the applications route is the first safe place to use the store. Another title for this question would be: Is it possible to set a service from a route in ember?




Aucun commentaire:

Enregistrer un commentaire