Retrieving a basic array of strings from the server using Ember.js

Can a simple JSON array be retrieved from the server and used as a constant lookup table in an Ember application?

I have a Rails controller that sends back a basic array of strings:

[ "item one", "item two", "item three", ...]
. I do not want these to be full Ember Models, nor do I want them represented as key:value pairs (so not like this:
[{name: "item one"}, {name: "item two"}, {name: "item three"}, ...]
)

How can I fetch the JSON array once and then reference it in my application?

For starters, I attempted to define a property on a controller that is then displayed in Handlebars using {{each}} tags:

controller:

window.App.SimpleController = Ember.Controller.extend(
  words: (() ->
    Ember.$.getJSON("http://localhost:3000/dictionary")
  ).property()
)

template:

{{#each words}}
    {{this}}
{{/each}}

Ember is showing an error that it's not an Array, but a jQuery promise object:

Uncaught Error: Assertion Failed: The value that #each loops over must be an Array. You passed {readyState: 1, getResponseHeader: ...

This is also confusing - I thought Ember could handle promises as arrays?

Answer №1

Ember is designed to handle promises returned to a model hook, rather than a computed property. It is recommended to set this up in a route or utilize a promise proxy for the computed property.

Typically, data fetching and setting is done in the route. However, if you prefer to use a computed property in the controller, you can employ the proxy pattern provided by Ember Data, which utilizes classes from Ember.

For an object response from the server, your computed property can be structured like this:

words: (() ->
  var foo = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin),
      promise = Ember.$.getJSON("http://localhost:3000/dictionary");
  foo.create({ promise: promise });
).property()

If the response is an array, you would set up an array proxy in a similar manner.

words: (() ->
  var foo = Ember.ArrayProxy.extend(Ember.PromiseProxyMixin),
      promise = Ember.$.getJSON("http://localhost:3000/dictionary");
  foo.create({ promise: promise });
).property()

If dealing with an array, there is another approach of returning an array reference and populating it later.

words: (() ->
  var foo = [],
      promise = Ember.$.getJSON("http://localhost:3000/dictionary");

  foo.then(function(data){ // this occurs asynchronously
    data.forEach(function(item){
      foo.pushObject(item);
    });
  });

  return foo;
).property()

Alternatively, you can simply set the property during the route setup: EmberJS: How to load multiple models on the same route?

Answer №2

It's true that Ember treats promises as arrays, but remember to actually return that array. I'm not familiar with rail syntax, but in regular syntax it would look something like this:

return Ember.$.getJSON("http://localhost:3000/dictionary").then(function(data){
     return data;
});

Also, make sure this code is in the route, not the controller.

I hope this explanation is helpful!

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 front-end angular application with npm and grunt commands

Hello there! This marks my first question, so please bear with me if it's a bit unclear. I'm fairly new to application development and currently working on an AngularJS app using Grunt. My query revolves around the build process I've execut ...

Is there a possibility of encountering an endless update loop within a component's render function?

Hello! I am a beginner in Vue.js and I have encountered an issue with my function. Instead of increasing my variable to 1 as expected, it is increasing it to a random number every time. The console is displaying the following error message: "You may hav ...

The useEffect hook is not successfully fetching data from the local db.json file

I'm attempting to emulate a Plant API by utilizing a db.json file (with relative path: src\plant-api\db.json), and passing it from the parent component (ItemList) to its child (Item) but I am facing an issue where no data is being displayed ...

What is the best way to halt a jQuery function when hovering over it?

Currently, I have a jQuery function set up to run on setInterval(). However, I am looking for a way to pause the interval when hovering over the displayed div and then resume once no longer hovering (i.e., continue cycling through the divs). Does anyone ...

What is the process for integrating custom event information stored in the {} property of a highchart dataset into highcharts-vue?

Creating charts with Vue using JSON data passed into the :options tag has been my usual approach. However, I am now experimenting with constructing a custom chart by utilizing the renderer and ren.path().attr().add() functions. The load function within th ...

Displaying JSON data obtained from two separate arrays in AngularJS - is it possible?

I want to display the value of my Json element, "Baru20151","Lama20151","Baru20152","Lama20152", but I'm unsure how to do it. The element is fetched from 2 arrays, for the "Baru20151" elements, "20151" is obtained from the "isimasa" array in my Jso ...

Updating a database on ASP.NET without the need to refresh the page

We are developing a user-friendly application with ASP.NET MVC that focuses on uploading pictures and rating them. The app includes two voting buttons, "like" and "dislike". https://i.sstatic.net/Z3dp5.png Whenever the like button (green) is clicked, the ...

Guide on how to retrieve information from an API and populate it into a dropdown menu

Currently, I am developing an MVC application that interacts with an API. My goal is to call a specific method from the API in order to populate data into a combo-box. However, as a newcomer to this technology, I am unsure of the best approach to take. An ...

Navigating pointers and handling segmentation faults in the C programming language

Attempting to extract some float values from a file and store them in an array that has been initialized as follows: float *taps[3]; The data extraction process looks like this: for (i = 0; i < 3; i++) { fscanf(tapsInput, "%f", taps[i]); } I underst ...

Is there a way to change the border property of an element when clicked, without causing the displacement of other elements?

I'm in the process of creating a webpage where users can choose the color and storage capacity of an item. Only one color/capacity can be selected at a time, and once chosen, it should be highlighted with a border. The issue I encountered is that whe ...

Looking to convert this single object into an array of objects within VueJS

So, I've encountered a bit of a pickle with the data from an endpoint that I need to format for a menu project I'm working on. It's all jumbled up and not making much sense right now. Any assistance would be greatly appreciated! This is the ...

What is the best way to control the amount of rows displayed in my gallery at any given time?

I need help with customizing my gallery that is dynamically generated from a directory using PHP. My goal is to display only 2 rows of 4 images each, totaling 8 images, with a "show more" button for loading additional rows. How can I set a limit on the n ...

Establishing a Table of Disarray

I've hit a roadblock and I'm feeling confused about where to go next. Currently, I'm exploring the use of JavaScript to create tables for my data and display them in HTML. While I've successfully created the HTML table, I'm facing ...

The functionality for selecting text in multiple dropdown menus using the .on method is currently limited to the first dropdown

Having trouble selecting an li element from a Bootstrap dropdown and displaying it in the dropdown box? I'm facing an issue where only the text from the first dropdown changes and the event for the second dropdown doesn't work. <div class="dr ...

Refine JSON data by selecting only distinct key/value pairs

My JSON object has the following structure: var theSchools = { Bradley University: "bru", Knox College: "knox", Southern Illinois University Edwardsville: "siue",… } I am trying to find a way to retrieve the school name (key) based on the schoo ...

Splitting a foreach loop isn't functioning correctly

My coding expertise allows me to sort the list of cities by country: <?php $pdo = new PDO(...); $cities = $pdo->query('SELECT `city`, `country` FROM `cities` ORDER BY `id` ASC'); $cities->execute(); $data = array(); foreach($cities as $ ...

How can you transform a nested array into a flat JavaScript map?

If we consider a JavaScript Map structured like this: [ { id: 1, name: "Foo", contents: [1,2,3], morecontents: ["a","b"], }, { id: 2, name: "Bar", c ...

Using JavaScript to parse an XML document on a WAMP server

I am a beginner in the field of web development and currently struggling with parsing an XML document using JavaScript on WAMP server. I know that both the web page and XML file need to be on the same server for it to work. I tried placing both the PHP and ...

attempting to retrieve numerical variable beyond the function in jQuery

Trying to implement a star rating system and need to access the rating number for further actions. How can I make the number variable accessible outside of the click function? $(document).ready(function () { $(".li").mouseover(functio ...

Arrange search results using $in array parameter in MongoDB

My challenge involves managing two collections: users and items. Within the user.profile.savedItems array, items are saved in the following format: {"itemId" : "yHud5CWpdPaEc6bdc", "added" : ISODate("2014-09-12T22:28:11.738Z")} My goal is to retrieve ...