Ember.js Helper that mimics an Ajax request response

After extensive exploration and experimentation, it seems that returning a value from an ajax request in Emberjs is quite challenging. (I could be mistaken.) The issue appears to be related to the asynchronous nature of callbacks.

Here lies my predicament;

I have a parent model A with children of model B. My goal is to showcase both the parent and children together, along with additional information obtained through an api call leveraging data from model B. I do not intend to store this extra information on model B, but rather wish to display it. Essentially, the setup resembles this:

{{#each modelb in modela.modelbs}}
...
{{/each}}

It would be ideal to achieve something like this:

{{#each modelb in modela.modelbs}}
  {{get-info modelb}}
{{/each}}

Where the retrieved information from the api call is rendered.

I attempted using a helper as mentioned earlier. I also experimented with controller logic, however, isolating individual child models to create a computed property proved to be problematic. Additionally, I am uncertain if a computed property would address my needs, considering it requires a return statement. This loops me back to the original issue with helpers. Moreover, creating a computed property directly on the child relationship seems unattainable. While I have the necessary extra information from the api call, linking it with my child model B poses a challenge.

It appears that my approach to this problem may not align with the 'ember way'. Hopefully, there exists a more effective method to tackle this.

Any assistance on this matter would be sincerely appreciated.

Answer №1

This is the solution I came up with.

Within my route, I include the following:

export default Ember.Route.extend({
  //model is already loaded from parent route.
  setupController: function(controller, model){
    var modela = model; //just for clarity with the whole modela/modelb thing.
    modela.get('modelbs').forEach(function(modelb){
      $.ajax({
        //some ajax call using modelb's information.
      }).then(function(data){
        //extraInformation is not a model defined property on modelb, but I just added extraInformation as an index to modelb.
        modelb['extraInformation'] = data;
        controller.set('model', modela);
      });
    });
  }
});

In the template, I include:

{{#each modelb in modela.modelbs}}
  {{modelb.extraInformation}}
{{/each}}

I hope this explanation can assist someone experiencing the same issue.

Answer №2

One way to utilize the existing data is by including an identifier when calling modelA or ModelB functions. This identifier can then be used in the callback function to correctly associate the data with the respective model.

Here's a simplified example:

var objects = [
    {id:1, message: "Hello", additionalInfo: ""},
    {id:2, message: "Goodbye", additionalInfo: ""}
];

for(var i = 0; i < objects.length; i++){
    retrieveAdditionalData("additionalInfo", objects[i].id);
}

function retrieveAdditionalData(parameter, 1){
    // make call
    // on success
    linkDataToObject(result, 1);
}
function linkDataToObject(data, id){
    for(var i = 0; i < objects.length; i++){
        if(objects[i].id === id){
           objects[i].additionalInfo = data;
        }
    }
}

Answer №3

To retrieve information about modelb in modela's afterModel hook, you can use the following code as an example:

App.ModelaRoute = Ember.Route.extend({
  model: function(params) {
    return this.store.find('modela', params.id);
  },
  afterModel: function(modela) {
    // Note: afterModel is executed after modela is loaded

    // Iterate through modelbs
    modela.get('modelbs').foreach(function(modelb) {
      // Retrieve additional information for current modelb via ajax. Keep in mind that multiple ajax requests may be triggered - which could be undesirable
      ajaxRequestForModelbInfo.done(function(response) {
        // Set extra information to modelb's extraInformation property
        modelb.set('extraInformation', response);
      });
    });
  }
});

In the hbs template file:

{{#each modelb in modela.modelbs}}
  {{modelb.extraInformation}}
{{/each}}

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

Creating a Loopback API that seamlessly integrates with Ember.js

Exploring the use of Loopback to create an API that communicates with Ember. Ember expects JSON data to be enclosed in 'keys', such as for an account: { account: { domain: 'domain.com', subdomain: 'test', title: ...

Breaking auto-update functionality when using the 'dd-slick' jQuery plugin to style chained drop-downs

Utilizing the jquery.ddslick.min.js plugin from jQuery for creating customized drop-down menus with image options. Additionally, incorporating the jquery.chained.min.js script to automatically update the content in the second select box based on the select ...

Submitting a specific group of form inputs using ajax involves selecting the desired elements within the form

My task involves dealing with a large form that needs to be submitted in PHP, which poses a challenge due to the maximum input variable limits in PHP +5.3 as discussed on this Stack Overflow thread. Instead of submitting everything from the form, I only n ...

Connecting HTML POST to MongoDB using NodeJS

I am in the process of developing a blog application using Node, Express, and MongoDB. My goal is to create an HTML form that will allow users to submit new blog posts directly to the database. While I have successfully implemented GET and POST requests us ...

Simplified React conditional rendering made easy

Currently, I am utilizing React 16 with Material-Ui components. In my root component, I have a requirement to load a tab and a view conditionally based on a property. Although I have managed to implement this functionality, the code appears quite messy a ...

How can we integrate fixed-data-table-2 sorting with an existing redux store?

Any help or advice you can offer would be greatly appreciated. I am still fairly new to using react. I recently took on a project for a client that was already in progress, and everything has been going smoothly up until now. I've come across a stumb ...

Submitting a file using Ajax XMLHttpRequest

Currently, I am facing an issue while attempting to send a file using the following XMLHttpRequest code. var url= "http://localhost:80/...."; $(document).ready(function(){ document.getElementById('upload').addEventListener('cha ...

Do not include the ajax request during the redirection process

I am facing an issue with my Ajax form that has 3 buttons for submission and cancellation. The Post request is processed correctly, but when it redirects to the next page, the new Action identifies it as an Ajax request and returns a partial page instead o ...

Having trouble loading a React component

I've been working on breaking down modules from a monolithic React project to store them separately in my npm registry. However, I'm encountering issues with exporting and importing them correctly. Previously, I was using the following code: con ...

Converting dynamic content within a div into an interactive link

I am currently working with Longtail's JW Player and facing some difficulties with a basic function. Since I am not familiar with the programming language terminologies, I will describe the issue step by step: There is a JavaScript code that displays ...

What is the process for filtering out a particular version of an npm package?

Here is my current configuration: "@vue/test-utils": "^1.0.0-beta.25" Can anyone recommend a way to exclude a particular version of this package while still using the caret ^ notation? I specifically need to exclude version 1.0.0-beta.31 as it has cause ...

Installing libraries using npm can be done in two ways: using the command `npm install`

While working, we encountered an issue where the icon for the menu block from the rc-menu library was not displaying. Every time we run mvn install We also run npm install In our package.json file, we had included this library "rc-menu":"^5.1 ...

Tips for resizing a tooltip using CSS

I am currently working on customizing tooltips and would like them to display right below the hover text in a responsive manner, with the ability to have multiline text. Instead of spreading horizontally, I want the tooltip to expand vertically based on th ...

Verifying the existing user in a personalized Ajax form that is used to update a Woocommerce order

Currently, I am developing a form that allows users to update specific order details, such as expenses and the reason for the expense. After updating the order, a JavaScript alert confirms the successful update, and the order's metadata is updated acc ...

jQuery includes inArray as the final element in an array or object

There's a strange issue I've noticed where, in some cases, when jQuery is imported, it appends the inArray function as the last element of a defined object or array. This can cause problems with for ... in loops since it counts this unexpected fu ...

Retrieve dynamic data for Pivot in Devexpress AngularJS

I am currently working on an AngularJS web app where I am implementing a Pivot using devexpress, specifically utilizing the Field Chooser. You can find the example code here: In the provided example, static data is used. However, I need to fetch data dyna ...

Codepen fails to function properly after being uploaded to a server

I have encountered an issue with my code on CodePen. After exporting it as a .zip file and attempting to run it on a local server, it failed to work. I am unsure of the exact reason behind this. I made sure to include all the necessary dependencies in the ...

Animated Content Sliding out Smoothly from Right to Left Using jQuery

I am attempting to implement a slideout function from the right side using jQuery. I have tried modifying the code for "From Left to Right" but it doesn't seem to be working correctly. Can you please provide me with guidance on how to make the necessa ...

Unexpected restarts are occurring in a lengthy PHP script

I have a PHP script that I execute using the $.ajax() Javascript function: $.ajax({ type: "POST", url: "/myscript.php", data: $("#my-form").serialize() }); Details of myscript.php class myclass{ public function __construct(){ $i ...

Why does the styling of the inner Span adhere to the style of the outer Span?

How can I adjust the opacity of the color "blue" to 1 in the code snippet below? <!DOCTYPE html> <html> <body> <p>My mom's eyes are <span style="color:blue;font-weight:bold;opacity:0"> <span style="color:blue;fo ...