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

The forEach method in JavaScript seems to work asynchronously

After reviewing other discussions on this platform, it seems that the general agreement is that forEach should be synchronous and block. However, in my code, something appears to be off as it doesn't behave that way: var noDupes = false; // se ...

What is the best way to duplicate/rename/replace an image in PHP while utilizing form submission and radio buttons?

I am new to PHP and I am working on a feature that allows a user to change an image using radio buttons and form submission. The goal is to copy and rename one of two image files (Open/Closed.jpg) to another location (images/status/Status.jpg) without requ ...

How to use ngModel directive in Angular to select/unselect dynamically generated checkboxes and retrieve their values

Currently, I am working with a dataset retrieved from an API and dynamically creating checkboxes in my HTML page using the DataView component from PrimeNG. My objective is to implement a feature where users can select or deselect all checkboxes with a cli ...

Is the memory efficiency of Object.keys().forEach() in JavaScript lower compared to a basic for...in loop?

Picture a scenario where you have an extremely large JS object filled with millions of key/value pairs, and your task is to loop through each of them. Check out this jsPerf example that demonstrates the different techniques for accomplishing this, highlig ...

The following middleware is not functioning properly on a local SSL server

When I run my Nextjs app without SSL using "next dev", the middleware functions as expected without any errors. However, if I attempt to run the app with SSL enabled, an empty middleware function triggers an error. The code for the middleware function (l ...

What's preventing me from drawing a line on this D3.js chart with my Angular code?

I am attempting to create a graph on my webpage using the D3.js library for JavaScript. I am able to draw a line on an SVG using HTML, but when I try to draw a line using JavaScript, I encounter the error message: ReferenceError: d3 is not defined. Even t ...

Using the Proper 'this' Reference Without Repeating 'this' in Nested Functions

I am facing an issue in my class where I have multiple methods and properties. One of these methods contains a setTimeout() function as follows: function myClass() { this.some_property = "test"; this.PrintOnTimeout = function() { // I thou ...

Troubleshooting $digest problems with AngularJS and the selectize directive

I am encountering difficulties when utilizing the watch function within a directive in conjunction with a third-party plugin named selectize. Despite researching extensively about $digest and $watch, I am still facing issues. Although my example below is ...

observing the value of the parent controller from the UI router state's resolve function

I am facing an issue in my AngularJS application while using ui-router. There are three states set up - the parent state controller resolves a promise upon a successful request, and then executes the necessary code. In the child state portfolio.modal.pate ...

When using React and React Router v6, make sure to implement a 404 status code response for unmatched routes

When it comes to managing unmatched routes with React Router, I have a solid understanding: <Routes> {/* Public routes */} <Route exact path="/" element={<Home />} /> // Other routes... {/* Error routes */} ...

Working with AngularJS: binding data to dynamically appended HTML elements using JavaScript

Is there a way to connect an angular event and model to an html element that is added through javascript code? To see my code, click here: https://jsfiddle.net/hq7qk48n/13/ <div ng-app> <div ng-controller="MyController"> <input ...

What steps are necessary to activate javascript in HTML for WebView?

I recently discovered that when my HTML/JavaScript site is visited via an Android webview, JavaScript is disabled by default. This causes a pricing list on my page to not display properly because it requires a JavaScript class to be added for it to open. I ...

What is the process for transferring an environment.json file to the output directory and then utilizing it with Webpack 4?

Our application is expanding with multiple environments and vendors on the horizon. While the traditional approach of running webpack --env.NODE_ENV=myenvironment works for now, it will soon become inefficient. The main objective here is to streamline the ...

Is it necessary to always pause before I click?

Currently, I am in the process of writing tests for my website using WebdriverIO with Mocha and Chai. However, I encountered an issue where my element is not rendered before attempting to interact with it. it('select application', function(done) ...

Learn the step-by-step process of clicking on a button to modify its properties and deactivate it

I could really use some assistance. I'm trying to make a button: <v-btn dark color="primary" class="square">Tile 1</v-btn> Is there a way I can modify it so that when clicked, it changes to flat, becomes disabled, and switches its color ...

Encountered an error in Discord.js: Undefined properties unable to be read (execute)

Here is the code snippet from my main file: const { Client, IntentsBitField, Collection, intents, SlashCommandBuilder } = require('discord.js') const { TOKEN, PREFIX } = require('./config.json') const fs = require('fs'); const ...

"Encountering a challenge when trying to fetch the value of an undefined or null

When it comes to validating the delivery date entered, I have implemented the following code to ensure it is not earlier than the current date... I have utilized custom validation using jQuery... Here is my model: [UIHint("Date")] [DeliveryDateC ...

Having difficulty grasping the concept of toggleClass and jQuery selectors

I am struggling to understand the getLiveSearchUsers function in my JS file. Could someone please help me? I don't quite grasp what selector[0] is and what toggleClass is doing here. $.post("includes/handlers/ajax_search.php", {query:value, userLogge ...

Creating a JSON array using looping technique

I am attempting to construct a JSON array using a loop where the input className and value will serve as the JSON obj and key. However, I am facing difficulties in creating one and cannot seem to locate any resources on how to do so. Below is an example sn ...

Unable to assign a value to a null property during the onchange event

I'm currently working on a project where I need to display flight details based on the selected flight number. To achieve this, I have created a dropdown menu that lists all available flight numbers and a table displaying various flight details such a ...