简体   繁体   中英

Ember.js Return promise in ApplicationRoute when setting multiple controller models

I need to set multiple models of controller in the applicationRoute models hook:

model: function() {    
    this.controllerFor('markets').set('model', this.store.pushPayload('market', marketsCache)); 
    this.controllerFor('pages').set('model', this.store.pushPayload('page', pagesCache)); 
    this.controllerFor('categories').set('model', this.store.pushPayload('category', categoriesCache)); 
    this.controllerFor('employees').set('model', this.store.pushPayload('employee', employeesCache));
}

In my webservers index.php file I set the javascript variables marketsCache , pagesCache , categoriesCache , and employeesCache . They are retrieved from APC cache, because the API is query intensive.

As you can see, I want the app to wait for the model to fullfill. However, promises are only for AJAX requests as far as I know. So, the question is, is it possible to wrap those controllerFor lines in a promise?

pushPayload doesn't return a promise nor a model at all, but you can push the payload, then call all which returns all the records in the store for that type, then you can assign it to the controllers.

model: function() {    
    this.store.pushPayload('market', marketsCache);
    this.store.pushPayload('page', pagesCache)
    ....

    var market = this.store.all('market'),
        pages = this.store.all('page');
    ....

    this.controllerFor('markets').set('model', model.market); 
    this.controllerFor('pages').set('model', model.pages); 
    ....
}

You can accomplish this with jQuery Deferred/When:

var market = this.store.pushPayload('market', marketsCache);
this.controllerFor('markets').set('model', market); 

var page = this.store.pushPayload('page', pagesCache);
this.controllerFor('pages').set('model', page); 

var category = this.store.pushPayload('category', categoriesCache);
this.controllerFor('categories').set('model', category); 

var employee = this.store.pushPayload('employee', employeesCache);
this.controllerFor('employees').set('model', employee);

return $.when(market, page, category, employee);

Docs: https://api.jquery.com/jQuery.when/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM