Skip to content

Commit

Permalink
Merge pull request #11525 from rwjblue/add-helpful-error-for-duplicat…
Browse files Browse the repository at this point in the history
…e-keys

[BUGFIX release] Add helpful error for {{each}} with duplicate keys.
  • Loading branch information
rwjblue committed Jun 21, 2015
2 parents f896a89 + baee94a commit 8ee36cb
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
7 changes: 7 additions & 0 deletions packages/ember-htmlbars/lib/helpers/each.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Ember from 'ember-metal/core';
import Error from 'ember-metal/error';
import normalizeSelf from 'ember-htmlbars/utils/normalize-self';
import shouldDisplay from 'ember-views/streams/should_display';
import decodeEachKey from 'ember-htmlbars/utils/decode-each-key';
Expand Down Expand Up @@ -79,13 +80,19 @@ export default function eachHelper(params, hash, blocks) {
}

if (shouldDisplay(list)) {
let seenKeys = {};
forEach(list, (item, i) => {
var self;
if (blocks.template.arity === 0) {
self = normalizeSelf(item);
}

var key = decodeEachKey(item, keyPath, i);
if (seenKeys[key] === true) {
throw new Error(`Duplicate key found ('${key}') for '{{each}}' helper, please use a unique key or switch to '{{#each model key="@index"}}{{/each}}'.`);
} else {
seenKeys[key] = true;
}
blocks.template.yieldItem(key, [item, i], self);
});
} else if (blocks.inverse.yield) {
Expand Down
34 changes: 34 additions & 0 deletions packages/ember-htmlbars/tests/helpers/each_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1302,5 +1302,39 @@ QUnit.test('can specify `@identity` to represent mixed object and primitive item
equal(view.$().text(), 'foobarbaz');
});

QUnit.test('duplicate keys trigger a useful error (temporary until we can deal with this properly in HTMLBars)', function() {
runDestroy(view);
view = EmberView.create({
items: ['a', 'a', 'a'],
template: compile('{{#each view.items as |item|}}{{item}}{{/each}}')
});

throws(
function() {
runAppend(view);
},
`Duplicate key found ('a') for '{{each}}' helper, please use a unique key or switch to '{{#each model key="@index"}}{{/each}}'.`
);
});

QUnit.test('pushing a new duplicate key will trigger a useful error (temporary until we can deal with this properly in HTMLBars)', function() {
runDestroy(view);
view = EmberView.create({
items: A(['a', 'b', 'c']),
template: compile('{{#each view.items as |item|}}{{item}}{{/each}}')
});

runAppend(view);

throws(
function() {
run(function() {
view.get('items').pushObject('a');
});
},
`Duplicate key found ('a') for '{{each}}' helper, please use a unique key or switch to '{{#each model key="@index"}}{{/each}}'.`
);
});

testEachWithItem('{{#each foo in bar}}', false);
testEachWithItem('{{#each bar as |foo|}}', true);

0 comments on commit 8ee36cb

Please sign in to comment.