How to Retrieve Parent Value from Child in Ember Data

I am encountering an issue with the widget model that has a simple parent-child structure. A widget can either be a standalone "root" widget or a child widget with a parent.

Here is the Ember data model representation:

export default DS.Model.extend({
  name:         DS.attr('string'),
  parentWidget: DS.belongsTo('widget', { async: true, inverse: null }),
  isSubWidget:  DS.attr('boolean')
})

I am trying to incorporate a "displayName" property that displays the name for root widgets and shows the combination of parent and child names for child widgets.

displayName: Ember.computed('name', 'parentWidget.name', 'isSubLob',  function() {
  if this.get('isSubWidget') {
    return "#{this.get('parentWidget.name')} - #{@get('name')}"
  }
  else {
    return "#{this.get('name')}"
  }
})

However, there seems to be an issue as the child widget's displayName always appears as

undefined - WidgetName

The JSON response looks like this:

{
"widgets": [
  {
    "id": 2,
    "name": "Widget Name",
    "is_sub_widget": true,
    "parent_widget_id": 1
  },
  ...
}

All the records are returned simultaneously in the JSON response.

I assume that Ember should asynchronously resolve the parent widget and update the string accordingly, but it does not seem to work as expected. Can anyone point out what might be going wrong here?

Answer №1

You seem to be facing two key issues:

  1. The first issue lies in the declaration of the inverse for your parentWidget relationship. Ember Data is currently left guessing the inverse, which may lead to incorrect assumptions. Update the declaration as follows to provide clarity:

    parentWidget: DS.belongsTo('widget', { async: true, inverse: null }),
    

    This adjustment may not directly solve your problem but it's a recommended best practice.

  2. Your second issue stems from not waiting for the promise to resolve before utilizing the name property. Since you've set the parentWidget relationship as asynchronous, calling @get('parentWidget') will return a promise rather than an immediate model. To ensure proper functionality, modify the computed property definition to watch relevant keys:

    displayName: Ember.computed('name', 'parentWidget.name', function() {
    

    Remember, initially parentWidget.name will be undefined until the promise resolves, causing the computed property to run multiple times before obtaining the desired value.

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

Differences in Regular Expressions between Chrome and Internet Explorer

I'm working with this regular expression: var SSN_REGEX = /^[A-Åa-å0-9,\!\-\?\""\. ]{3,999}$/; This regex is used in a JavaScript function where I check for social security numbers. function validateSSN(ssn){ if (SSN_RE ...

"Experience the new Bootstrap 5 feature: Off-Canvas sliding from left to

I encountered the code snippet below on the official bootstrap 5 demo. Despite my efforts, I am struggling to figure out how to relocate the off-canvas menu from Left-to-Right. The divergence between the documentation code referencing offcanvas-start and t ...

Is there a way to execute a jQuery code once an angular function has been loaded?

After uploading an image through Angular using ng-file-upload, I want to display it and initialize a jQuery plugin called Cropper. Is there a way to execute the jQuery code from this point? It seems that it only works when $scope.loadedImage is loaded bef ...

Are you making alterations to the URL?

Is there a way to change the displayed URL on a webpage to show "bananas" instead of "http://example.com/" after the page has loaded? ...

Utilize Material UI's Datagrid or XGrid components to customize the rendering

There is a section from Material UI discussing renderHeader in the DataGrid and Xgrid components. https://material-ui.com/components/data-grid/columns/#render-header The documentation describes how to add additional content to the header, but what if I w ...

Executing a Vue method from the main.js file within a Vue.js document

Why can't I call my method in App.vue? Shouldn't the div with id='App' in the App file allow me to access methods within it? Main.js new Vue({ render: h => h(App), methods:{ gesamt:function () { return 'Hello&a ...

Executing JavaScript code within an iframe using the AMP framework

Currently, I am utilizing Next.js with AMP functionality enabled. For more information, check out: https://nextjs.org/blog/next-8-1 However, I have encountered an issue where any JavaScript included in my React code is only executed on the server side and ...

The html carousel displays stacked images instead of scrolling

I have been staring at this code for what feels like an eternity, trying to figure out why it's only displaying stacked pictures instead of a functioning carousel. Perhaps I overlooked something crucial. Could someone please lend a hand? My code is pr ...

Angular can redirect the path to the current page

I am looking for a way to handle empty paths in my routing module by redirecting to the current page. Can someone help me achieve this? Thank you in advance. Below are the routes defined: const routes: Routes = [ { path: 'students', co ...

Changing Axios requests to send data as a JSON objectDo you need to know how

Looking at the title, there is a scenario where you execute a axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (erro ...

angular-cli build error in monorepo: TS2451: 'ngDevMode' variable cannot be redeclared

In my development environment, I have organized a monorepo with two distinct packages. The first package is the primary application, known as app, while the second package is a shared library that is utilized by the main application, referred to as lib. Bo ...

What is the most effective method to prevent the auto-complete drop-down from repeating the same value multiple times?

My search form utilizes AJAX to query the database for similar results as the user types, displaying them in a datalist. However, I encountered an issue where it would keep appending matches that had already been found. For example: User types: "d" Datali ...

What is the best way to dynamically change the style options of a select dropdown based on a specific condition?

My knowledge of JavaScript is limited, but I require some JS functionalities for my Django project. Your assistance would be greatly appreciated. I want to customize the style of option tags within the select tag with the id "id_car_model". The goal is to ...

Having trouble with the auto-complete feature in the search box when using Jquery

I'm currently working on implementing TypeAhead functionality for a search textbox. Within the form, I have 2 radio buttons and if one of them is selected, I need the type-ahead feature to populate the list of masters in the search box. //html < ...

How can I send an API request with a callback function as an argument using node.js?

If you want to access the getPlayers(callback) method, it is described as follows: getPlayers(callback) callback - This parameter is necessary. It will be called with an object of players players - An object that contains all the players who are curr ...

I'm having trouble getting the infoWindow to function properly

As someone who is new to JavaScript, I recently came across a question on Google Maps JS API v3 - Simple Multiple Marker Example and attempted to implement the solution provided by Daniel Vassallo. var Australia = new google.maps.LatLng(-27.16881, 132.7 ...

Error: The program is unable to find the specified property to match, resulting in an undefined error

I am currently working on a project in React JS where I need to display text instead of a profile image if it is not available. To achieve this, I have created a function that takes the current customer's name as input and extracts the first character ...

After filtering the array in JavaScript, perform an additional process as a second step

My task involves manipulating an array through two methods in sequence: Filter the array Then, sort it The filter method I am using is as follows: filterArray(list){ return list.filter(item => !this.myCondition(item)); } The sort method I a ...

ng-repeat isn't displaying the data

I have always been comfortable using the ng-repeat in Angular, but this time I seem to be facing a problem. I am trying to populate my DOM with data from a JSON file, but for some reason, the fields are not displaying as expected. Is there something wrong ...

Is there a way to automate the duplication/copying of files using JavaScript?

I have a GIF file stored in the "assets" directory on my computer. I want to create multiple duplicates of this file within the same directory, each with a unique filename. For example: If there is a GIF file named "0.gif" in the assets directory, I woul ...