Joe Czucha
Joe Czucha

Reputation: 4295

Using this.store.query() in a computed property

I've build a custom dropdown element and I'm trying to use it to display a couple of things:

{{drop-down items=types selectionChanged="typeChanged"}}

{{drop-down items=meters selectionChanged="meterChanged"}}

In my controller I'm setting the values as follows:

types: [
  { value: "latest", name: "Latest Widget" },
  { value: "max", name: "Maximum Widget" },
  { value: "average", name: "Average Widget" },
],

meters: Ember.computed(function() {
  var meters = this.store.query('meter', { account_id: 2 });
  return meters;
}),

The values for both are appearing correctly:

<select id="ember826" class="ember-view form-control">
  <option value="">Please select a widget type...</option>
  <option value="latest">Latest Widget</option>
  ...
</select>

<select id="ember849" class="ember-view form-control">
  <option value="2">Meter 1</option>
</select>

My drop-down component uses the following to work out the selected value:

change: function(event) {
  var items = this.get('items');
  var index = event.target.selectedIndex;
  var selected = items ? items[index - 1] : null;
  console.log(selected); // error occurs here
  this.sendAction('selectionChanged', selected);
}

Now this works just fine for 'types' but for 'meters', selected is "undefined".

I then added console.log(JSON.stringify(items)); just before that line and, for the meters change, it gave me the following error:

Uncaught TypeError: Converting circular structure to JSON

If I add {{log types}} and {{log meters}} to the template, I get the following, which may shed some light on it:

Types:

Result of {{log types}}

Meters:

Result of {{log meters}}

I notice that the latter has it wrapped in a couple of layers of 'content' keys so maybe the promise isn't being resolved properly?

Edit

If I use this.store.query in a route and then {{log}} the model then it's wrapped in a single 'content' key, which Ember can correctly interpret. Is there any reason why doing this in the controller should create the extra one?

Upvotes: 4

Views: 1296

Answers (1)

Kingpin2k
Kingpin2k

Reputation: 47367

use objectAt to access items from an Ember Collection.

change: function(event) {
  var items = this.get('items');
  var index = event.target.selectedIndex;
  var selected = items ? items.objectAt(index - 1) : null;
  console.log(selected); // error occurs here
  this.sendAction('selectionChanged', selected);
}

Upvotes: 1

Related Questions