Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ember 1.13 and later what key should I use with each when iterating over an array of strings?

In Ember 1.13 the following code generates a warning:

{{#each widgetNames as |widgetName|}}
  {{component widgetName removeWidget="removeWidget"}}
{{/each}}

Where widgetNames is an array of strings in a parent controller.

widgetNames: []

In Ember 1.13 I now get this warning:

WARNING: Using {{each}} without specifying a key can lead to unusual behavior. Please specify a key that identifies a unique value on each item being iterated. E.g. {{each model key="@guid" as |item|}}.

This would be easy enough to fix in you typical model scenario, but how do I specify a key for an array of strings?

Edit: This question handles a warning you now get in Ember 1.13 when iterating over an array of strings. If you hit this warning you are not explicitly looking to find the @index parameter like Accessing Index in #each in emberjs. Infact, Artych's answer shows two other possible keys to use that would not be relevant or present in an answer to Accessing Index in #each in emberjs as this is specific to the @index parameter itself.

like image 599
Adam Knights Avatar asked Jun 15 '15 12:06

Adam Knights


1 Answers

UPDATE (Jun,18) In Ember 1.13.2 default key="@identity" is used, to prevent users from having to specify a key= to each {{each}} invocation.

@guid and @item are deprecated in favor of the new default.

https://github.com/emberjs/ember.js/releases/tag/v1.13.2 https://github.com/emberjs/ember.js/pull/11461

================= Answer for Ember 1.13, 1.13.1 =========

You could use key="@index" or key="@item".

There are a few special values for key ( docs ):

  • @index - The index of the item in the array.
  • @item - The item in the array itself. This can only be used for arrays of strings or numbers.
  • @guid - Generate a unique identifier for each object (uses Ember.guidFor).

    {{#each widgetNames key="@index" as |widgetName|}}
       {{component widgetName removeWidget="removeWidget"}}
    {{/each}}
    
like image 113
artych Avatar answered Sep 29 '22 20:09

artych