Ember Gain a comprehensive understanding of the flow of execution between route and controller

Below is a snippet of my "box" route/controller:

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
    }
});

The structure of my route is as follows:

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); 
        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: {      
    }
});

This is how my template looks like:

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

Snippet of my doPost method:

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;
  }

As I was debugging the flow/sequence of execution in my setup, I encountered 2 specific questions:

  1. I noticed that the "gridParas" hook is executed before the "activate" hook, which was unexpected. Is this due to the presence of "gridParas" in the template?

  2. In order to ensure that the code inside filterCols() controller is executed only after receiving a response from /myService1, I had to make a "sync" request using this.doPost(). How can I achieve this with an "async" request without causing errors?

Just to mention, I am working with Ember v 2.0

Answer ā„–1

  1. activate() on the route is triggered after the beforeModel, model and afterModel hooks. These 3 hooks are part of the "validation phase" which determines if the route will resolve. This route hook does not relate to using gridParas in your template, but focuses on calling get('gridParas') within your model hook.
  2. The connection of doPost() to the rest of your code is not clear. However, since it returns a promise object, you can chain a then() function to wait for the response before using it in your code further.

Here is a simple example:

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

If you can provide a clearer and more concise question, I may be able to offer additional insight.

Answer ā„–2

Typically, at this stage, it is important to clarify your objectives rather than just inquiring about the process itself. It seems like there may be some resistance against the framework!

Let's address your concerns.

To begin with, you can eliminate your doPost method! Utilize jQuery's $.ajax, which returns a thenable that can be converted into a Promise using Ember.RSVP.resolve.

Furthermore, if you intend to retrieve data before rendering anything, it should be done within the model hook.

It's unclear whether you need to fetch data from /service1 first and then make a subsequent request to

/service2</code, or if you can independently fetch both services and display the combined data (perhaps in a grid). Let's explore both scenarios:</p>

<hr />

<p>If you can fetch both services independently, implement the following in your routes' <code>model
hook:

return Ember.RSVP.hash({
  service1: Ember.RSVP.resolve($.ajax(/*your request to /service1 with all necessary data and parameters, potentially utilizing query-params*/).then(data => {
    return data; // extract the required data, perform any necessary transformations.
  },
  service2: Ember.RSVP.resolve($.ajax(/*your request to /service2 with all necessary data and parameters, potentially utilizing query-params*/).then(data => {
    return data; // extract the required data, perform any necessary transformations.
  },
});

If the response from /service1 is needed to fetch data from

/service2</code, follow this approach in your model hook:</p>

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

If these solutions do not address your issues (though I believe they should resolve them), please provide further details about your problem.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript's version of "a certain phrase within a text"

If I'm working in Python and need to verify if a certain value is present in a string, I would use: if "bar" in someString: ... What would be the equivalent code in Javascript for this task? ...

PHP Ajax file uploads can be tricky, as they often result in the frustrating "undefined

Encountering issues with submitting file through ajax. Despite following instructions from various sources, the formdata does not seem to contain the file resulting in an 'undefined index 'image'' error. <form enctype: 'multip ...

Unsubscribing from a service method in Javascript using RxJS

After clicking a button, a function is triggered to execute. The function includes an method called "executeAction" that retrieves the current view and then passes it as a parameter to another view for future reference. async executeAction(action: ...

Automate Zoom join function with the help of puppeteer

Having trouble joining a Zoom meeting using Puppeteer, my code is not capturing the password field. Can anyone assist? Here is my code snippet: const puppeteer = require("puppeteer-extra"); const StealthPlugin = require("puppeteer-extra-plu ...

Is there a way to input the Sno data into the database in ascending order?

function table_insert(lease_ids){ var lease_id=lease_ids+1; var table = document.getElementById('table_data123'), rows = table.getElementsByTagName('tr'), i, j, cells, customerId; for (i = 0, j = rows.le ...

How can I include inline CSS directly within a string instead of using an object?

Is there a way to write inline CSS in a string format instead of an object format? I attempted the following, but it did not work as expected: <div style={"color:red;font-weight:bold"}> Hello there </div> What is my reason for want ...

Struggling to send information to the data layer on every page in Angular 9

Currently, I am in the process of integrating a GTM snippet into my Angular project. However, I have noticed that when the page is hard reloaded, it pushes data but does not do so during normal navigation. I have already added the GTM snippet provided by ...

"Master the art of creating a curved circular arrow using a combination of HTML, SVG, D3.js

I am looking to design an SVG circle with a fading stroke that blends into the background and features an arrow at one end. The goal is for the ring to fade out completely right above the arrow, similar to the visual reference provided in the image.view ex ...

The post method in Express.js is having difficulty parsing encoded data accurately

I'm currently working on an AngularJS code that sends a POST request like this: var req = { method: 'POST', url: 'http://localhost:3300/addInventoryItem', headers: { 'Content-Type': 'application/x-www-form- ...

Decision on how to exchange data (JSON or traditional method)

In my current project, I am developing a user-friendly application that allows users to design their own web interface using various tools. Users can create drag-and-drop elements and I need to store this data in a database once they finalize their desig ...

Tips for retrieving the checked status of a Material UI <Checkbox/> component and changing it to false upon clicking a different icon (such as a delete icon)

Greetings! I have encountered a problem that I am hoping someone can assist me with. I am looking for information or guidance on how to handle a specific issue. The challenge I am facing involves accessing the checked property of a material-ui <Checkbo ...

Encountering a problem where updating the selected option in a dropdown does not properly refresh the HTML

I am currently working with a dropdown menu containing countries. Initially, the selected item is set to Ukraine. <select id="country" name="country"> <option value="US">USA</option> <option value="UG">Uganda</option> ...

Exploring the power of "this" in Vue.js 2.0

Seeking help with a VueJS issue. I am trying to create a voice search button that records my voice and prints it out in an input form. <input type="text" name="inputSearch" id="inputSearch" v-model="inputSearch" class="form-control" x-webkit-speech> ...

What is the best way to retrieve the results of an indexedDb request beyond the limitations of its callback function?

I am working on a form that has an input box which I want to auto-complete with values from an IndexedDb objectStore. Currently, it is functioning with two overlapping input boxes, using a simple array. However, I am looking to make it work with the values ...

Checking the validity of subdomain names using JavaScript/jQuery

For users signing up, my form allows them to choose a subdomain for their account. The valid characters allowed in the subdomain are letters, numbers, and dashes. Spaces and most special characters should be filtered out. http://_________.ourapp.com To r ...

"Troubleshooting Problem with JSON Encoding in PHP and Parsing with getJSON in

Apologies if this sounds like yet another discussion on the topic, but I've been struggling for hours without finding a solution. I'm attempting to retrieve data from a MySQL database, generate a JSON using PHP, and then parse this JSON in JavaS ...

What is causing the net::ERR_CONNECTION_RESET in Node JS and ExpressJS?

Our application, built on ExpressJS and NodeJS, is hosted on a Linode server and served at port 3000. Although the app has been functioning well for a year, we have recently encountered consistent connection errors. The errors vary, but they are mostly re ...

"Exploring the versatility of using variables in jquery's .css

Iā€™m facing an issue where I need the rotation of a div to be based on the value stored in "anVar." This is what I currently have: function something() { $('.class').css('-webkit-transform:rotate('anVar'deg)') } The desi ...

VueJS fails to display table information

I am facing an issue with rendering data from my API using VueJS 2. Although the backend services are successfully sending the data, the HTML table does not display it. There are no errors shown in the debug console, and even the Vue Debug extension for Fi ...

I could use some assistance with deciphering JSON data

After using console.log to display the data I received, I observed an object structured as follows (I trimmed some details for clarity and used ... to indicate repetitive information): [ Submission { title: 'Untitled', content: { ur ...