How can Ember.js display multiple database-backed resources or models on a single page or route?

Currently, I am in the process of creating a test application using Ember.js to build a budget management tool. The structure includes a Budget object which holds properties such as the monthly limit and a brief description. Additionally, there are Expense objects containing details like name, spent amount, etc. Both sets of data are fetched from a server utilizing Ember Data's REST adapter.

HTML:

<body>
    <script type="text/x-handlebars" data-template-name="budget">
    <h2>{{name}} (€ {{amount}})</h2>
    </script>

    <script type="text/x-handlebars" data-template-name="expenses">
    <ul id="expense-list">
        {{#each model}}
            {{render "expense" this}}
        {{/each}}
</ul>
</script>

    <!-- expense template -->
    <script type="text/x-handlebars" id="expense">
        <li>
            <label>{{description}}</label>
            <label class="subtle">{{formatDate time}}</label>
            <label class="amount">{{amount}}</label>
        </li>
    </script>
</body>
</html>

JavaScript:

window.App = Ember.Application.create();

App.ApplicationAdapter = DS.RESTAdapter.extend({
    host: 'http://localhost:5000',
    namespace: 'outthepocket/api'
});

// Model
App.Expense = DS.Model.extend({
    amount: DS.attr('number'),
    description: DS.attr('string'),
    time: DS.attr('date')
});

App.Budget = DS.Model.extend({
    name: DS.attr('string'),
    amount: DS.attr('number')
});

// Routes
App.Router.map( function() {
    this.resource('budget');
    this.resource('expenses');
});

App.ExpensesRoute = Ember.Route.extend({
    model: function()
    {
        return this.store.find('expense');
    }
});

App.BudgetRoute = Ember.Route.extend({
    model: function()
    {
        return this.store.find('budget', 1);
    }
});

In line with the standard Ember tutorials, I have an ExpensesRoute providing the list of expenses as its model and a BudgetRoute supplying the chosen budget as its model. This setup functions smoothly when I access each resource through their respective URL paths:

  • myapp.html#budget displays the budget template with relevant server data.
  • myapp.html#expenses showcases the expenses template alongside corresponding server data.

The challenge arises when I attempt to show both templates, along with their data, on a single page (the index page). I experimented with two solutions so far:

  • Solution 1: Employ separate routes and templates then use {{render budget}} and {{render expenses}} within the main application template. Although this method renders both templates, it does so without any associated data.

  • Solution 2: Opt for just an IndexRoute and retrieve both budget and expenses data in its model property, displaying them within the index template. This approach works to some extent, but goes against Ember's usual practice of handling various resources, routes, and controllers separately.

Any insights or suggestions? Despite reviewing several tutorials and Ember's official documentation, I haven't found a clear explanation on how to construct a one-page web app featuring multiple templates linked to distinct resources without the need for navigating to different pages or routes.

Answer №1

Utilize the Ember.RSVP.hash method to fetch multiple models within a single object:

App.IndexRoute = Ember.Route.extend({
    model: function()
    {
        return Ember.RSVP.hash({
            expenses: this.store.find('expense'),
            budget: this.store.find('budget', 1)
        })
    }
});

In your template, you can access each resolved promise using the respective key:

{{expenses}} will contain the result from the this.store.find('expense') promise and {{budget}} will hold the result from the this.store.find('budget', 1) promise.

Therefore, in your index template, you are able to:

<script type="text/x-handlebars" id="index">
    {{render "expenses" expenses}}
    {{render "budget" budget}}
</script>

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

Pass data from a Firebase JavaScript callback function in the Data Access Layer (DAL) to another function in the controller

I have been developing a basic chat application that enables users to send messages in a group chat and see them instantly updated. To achieve this, I opted for Firebase and spent time familiarizing myself with its web API. However, I encountered difficult ...

Angular2 faces a challenge with the selection issue

I have created a Plunker code for you to review. If you click the "toggle show" button twice, the selected item should be displayed. import {Component} from '@angular/core'; @Component({ selector: 'my-app', template: `<div *ngI ...

Unable to utilize a variable from React Context for accessing the value within an object

I'm facing a peculiar yet seemingly straightforward issue. My object named vatRates is structured as follows: const vatRates = { "AD": 0.00, "CZ": 1.21, "RO": 1.19, "DE": 1.19, "RS": 0.00, ...

Comprehending the process of routing from the client side (using JavaScript) to the server side (with Node

As a newcomer to web apps, I am currently trying to understand the process of routing from client side to server side and vice versa. Initially, I was successful in using xmlhttprequest on my client-side to fetch a JSON file while working locally. However, ...

I am encountering an error stating "Cannot locate module 'nestjs/common' or its related type declarations."

I am currently working on a controller in NestJS located in the file auth.controller.ts. import { Controller } from 'nestjs/common'; @Controller() export class AppController {} However, I encountered an error that says: Error TS2307: Cannot fin ...

Fulfill the specified amounts for each row within a collection of items

I have an array of objects containing quantities. Each object includes a key indicating the amount to fill (amountToFill) and another key representing the already filled amount (amountFilled). The goal is to specify a quantity (amount: number = 50;) and au ...

Incorporating jQuery UI Autocomplete with PHP and MySQL for a dynamic search

I seem to have encountered a minor issue that I'm struggling to identify... Basically, I've created a straightforward form that utilizes autocomplete to search for items in the database. However, this functionality only seems to work for the FIR ...

Issue with using indexOf in an array causing unexpected results

I am working on a JavaScript function to identify the character that appears most frequently in a given string, and then display this result in a div. Here is what I have so far: var string = "AABBCCDDEEEEEEEEEE"; var stringInput = document.getElementBy ...

Tips for hiding the window scrollbar and utilizing the freed-up space

I am currently working on a page that contains 2 vertically aligned divs. My goal is to always display the upper div to the user, while allowing for a scrollbar in the second div (which has a fixed height) as content expands. The issue I am facing is tha ...

I'm experiencing some compatibility issues with my script - it seems to be functioning correctly on desktops but not on mobile

Below is a script I've implemented on an html page to toggle the visibility of divs based on user interaction. <script> $(document).ready(function(){ $("#solLink").click(function(){ $(".segSlide").hide(), $(".eduSlide").hide ...

How should values be properly stored in a constant using mongoose?

Within my user model, I have included timestamps. I am seeking a way to retrieve the createdAt date and store it in a variable. My initial attempt was: const date = await User.find({ serial: serialId, }).select('-_id createdAt'); The result re ...

What is the best way to link buttons to specific drop down sections?

How can I create multiple drop down divs with different content for each button click? JSFiddle: http://jsfiddle.net/maddiwu/xe6xtfqh/ .slide { overflow-y: hidden; max-width: 100%; overflow-x: hidden; max-height: 100vw; /* approximate ...

Is my implementation of async await the most efficient method to handle asynchronous operations in my code?

Struggling to implement and grasp async await functions in my login example, I'm uncertain if my code is the most optimal, elegant, and clean. I especially have doubts regarding error handling, and how to best utilize const and functional programming ...

Is there a method to give a webpage a subtle shimmering effect without utilizing CSS box-shadow?

Struggling to Develop a High-Performance Interface Feature I'm currently facing a challenge in coding an interface that requires a subtle and broad glow effect, similar to the example provided below: https://i.sstatic.net/E4ilD.jpg Exploration of ...

Navigating through directories (including nested ones) containing images in React Native; what's the best way to approach this

I am currently attempting to organize groups of images. Within the directory ./assets, there are several folders structured as follows: ./assets ├── 1x3 │ ├── 1.jpg │ ├── 2.jpg │ └── 3.jpg └── 3x3 ├── 1. ...

Seems like ngAfterViewInit isn't functioning properly, could it be an error on my end

After implementing my ngAfterViewInit function, I noticed that it is not behaving as expected. I have a hunch that something important may be missing in my code. ngOnInit() { this.dataService.getUsers().subscribe((users) => {this.users = users) ; ...

Utilizing Titanium MVC: Invoke function and pause for response

Currently, I am in the process of developing my very first Titanium iPhone application. Within a model module, I have this code snippet: (function() { main.model = {}; main.model.getAlbums = function(_args) { var loader = Titanium.Ne ...

The window event listener is failing to trigger

Initially, my window listener was working perfectly fine. However, at some point in time, it suddenly stopped functioning properly. The resize event also ceased to work. I am completely clueless as to why it is no longer operational. mounted () { win ...

Comparing JavaScript and jQuery for form validation

Hey there, I'm currently working on a simple form validation for my submission. The validation is functioning correctly using a basic JavaScript function, but when I attempted to switch over to jQuery, it didn't work as intended. Below is the co ...

Configuring Google Maps API (including charts) for maximum height of 100%

I am having trouble getting my map to display at 100% height using the Google Maps API. I've encountered similar issues in the past with the Google Charts API as well. From what I've gathered, it seems like setting the height of the html and bod ...