简体   繁体   中英

Ember Understand execution flow between route/controller

I have a "box" route/controller as below;

export default Ember.Controller.extend({
    initialized: false,
    type: 'P',
    status: 'done',
    layouts: null,
    toggleFltr: null,
    gridVals: Ember.computed.alias('model.gridParas'),
    gridParas: Ember.computed('myServerPars', function() {
        this.set('gridVals.serverParas', this.get('myServerPars'));
        this.filterCols();

        if (!this.get('initialized')) {
            this.toggleProperty('initialized');
        } else {
            Ember.run.scheduleOnce('afterRender', this, this.refreshBox);
        }

        return this.get('gridVals');
    }),
    filterCols: function()
    {
        this.set('gridVals.layout', this.get('layouts')[this.get('type')]);
    },
    myServerPars: function() {
        // Code to set serverParas
        return serverParas;
    }.property('type', 'status', 'toggleFltr'),
    refreshBox: function(){
        // Code to trigger refresh grid
    }
});

My route looks like;

export default Ember.Route.extend({
    selectedRows: '',
    selectedCount: 0,
    rawResponse: {},
    model: function() {
        var compObj = {};
        compObj.gridParas = this.get('gridParas');
        return compObj;
    },
    activate: function() {
        var self = this;
        self.layouts = {};

        var someData = {attr1:"I"};
        var promise = this.doPost(someData, '/myService1', false); // Sync request (Is there some way I can make this work using "async")
        promise.then(function(response) {       
            // Code to use response & set self.layouts
            self.controllerFor(self.routeName).set('layouts', self.layouts);
        });
    },
    gridParas: function() {
        var self = this;
        var returnObj = {};
        returnObj.url = '/myService2';
        returnObj.beforeLoadComplete = function(records) {          
            // Code to use response & set records
            return records;
        };
        return returnObj;
    }.property(),   
    actions: {      
    }
});

My template looks like

{{my-grid params=this.gridParas elementId='myGrid'}}

My doPost method looks like below;

doPost: function(postData, requestUrl, isAsync){
    requestUrl = this.getURL(requestUrl);
    isAsync = (isAsync == undefined) ? true : isAsync;
    var promise = new Ember.RSVP.Promise(function(resolve, reject) {
        return $.ajax({
            // settings
        }).success(resolve).error(reject);

    });
    return promise;
  }

Given the above setup, I wanted to understand the flow/sequence of execution (ie for the different hooks). I was trying to debug and it kept hopping from one class to another. Also, 2 specific questions;

  1. I was expecting the "activate" hook to be fired initially, but found out that is not the case. It first executes the "gridParas" hook ie before the "activate" hook. Is it because of "gridParas" specified in the template ?

  2. When I do this.doPost() for /myService1, it has to be a "sync" request, else the flow of execution changes and I get an error. Actually I want the code inside filterCols() controller ie this.set('gridVals.layout', this.get('layouts')[this.get('type')]) to be executed only after the response has been received from /myService1. However, as of now, I have to use a "sync" request to do that, otherwise with "async", the execution moves to filterCols() and since I do not have the response yet, it throws an error.

Just to add, I am using Ember v 2.0

  1. activate() on the route is triggered after the beforeModel , model and afterModel hooks... because those 3 hooks are considered the "validation phase" (which determines if the route will resolve at all). To be clear, this route hook has nothing to do with using gridParas in your template... it has everything to do with callling get('gridParas') within your model hook.
  2. It is not clear to me where doPost() is connected to the rest of your code... however because it is returning a promise object you can tack on a then() which will allow you to essentially wait for the promise response and then use it in the rest of your code.

Simple Example:

this.doPost().then((theResponse) => {
  this.doSomethingWith(theResponse);
});

If you can simplify your question to be more clear and concise, i may be able to provide more info

Generally at this level you should explain what you want to archive, and not just ask how it works, because I think you fight a lot against the framework!

But I take this out of your comment.

First, you don't need your doPost method! jQuerys $.ajax returns a thenable, that can be resolved to a Promise with Ember.RSVP.resolve !

Next: If you want to fetch data before actually rendering anything you should do this in the model hook!

I'm not sure if you want to fetch /service1 , and then with the response you build a request to /service2 , or if you can fetch both services independently and then show your data (your grid?) with the data of both services. So here are both ways:


If you can fetch both services independently do this in your routes model hook:

return Ember.RSVP.hash({
  service1: Ember.RSVP.resolve($.ajax(/*your request to /service1 with all data and params, may use query-params!*/).then(data => {
    return data; // extract the data you need, may transform the response, etc.
  },
  service2: Ember.RSVP.resolve($.ajax(/*your request to /service2 with all data and params, may use query-params!*/).then(data => {
    return data; // extract the data you need, may transform the response, etc.
  },
});

If you need the response of /service1 to fetch /service2 just do this in your model hook:

return Ember.RSVP.resolve($.ajax(/*/service1*/)).then(service1 => {
  return Ember.RSVP.resolve($.ajax(/*/service2*/)).then(service2 => {
    return {
      service1,
      service2
    }; // this object will then be available as `model` on your controller
  });
});

If this does not help you (and I really think this should fix your problems) please describe your Problem.

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