From 1e6ae4e3f9d0f4eff621f9d23578d21026f4cb0a Mon Sep 17 00:00:00 2001 From: Travis Tidwell Date: Wed, 31 Jan 2018 20:15:15 -0600 Subject: [PATCH] Add ability to configure the item comparer function. --- README.md | 10 ++++++++++ src/scripts/src/choices.js | 2 +- src/scripts/src/constants.js | 1 + 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 711efc3..48d5f2b 100644 --- a/README.md +++ b/README.md @@ -99,6 +99,9 @@ Or include Choices directly: maxItemText: (maxItemCount) => { return `Only ${maxItemCount} values can be added.`; }, + itemComparer: (choice, item) => { + return choice === item; + }, classNames: { containerOuter: 'choices', containerInner: 'choices__inner', @@ -458,6 +461,13 @@ const example = new Choices(element, { **Usage:** The text that is shown when a user has focus on the input but has already reached the [max item count](https://github.com/jshjohnson/Choices#maxitemcount). To access the max item count, pass a function with a `maxItemCount` argument (see the [default config](https://github.com/jshjohnson/Choices#setup) for an example), otherwise pass a string. +### itemComparer +**Type:** `Function` **Default:** `strict equality` + +**Input types affected:** `select-one`, `select-multiple` + +**Usage:** Compare choice and value in appropriate way (e.g. deep equality for objects). To compare choice and value, pass a function with a `itemComparer` argument (see the [default config](https://github.com/jshjohnson/Choices#setup) for an example). + ### classNames **Type:** `Object` **Default:** diff --git a/src/scripts/src/choices.js b/src/scripts/src/choices.js index d40305d..64dafa6 100644 --- a/src/scripts/src/choices.js +++ b/src/scripts/src/choices.js @@ -2369,7 +2369,7 @@ class Choices { _findAndSelectChoiceByValue(val) { const choices = this.store.getChoices(); // Check 'value' property exists and the choice isn't already selected - const foundChoice = choices.find(choice => choice.value === val); + const foundChoice = choices.find(choice => this.config.itemComparer(choice.value, val)); if (foundChoice && !foundChoice.selected) { this._addItem( diff --git a/src/scripts/src/constants.js b/src/scripts/src/constants.js index 36070a8..5c377de 100644 --- a/src/scripts/src/constants.js +++ b/src/scripts/src/constants.js @@ -64,6 +64,7 @@ export const DEFAULT_CONFIG = { uniqueItemText: 'Only unique values can be added.', addItemText: value => `Press Enter to add "${value}"`, maxItemText: maxItemCount => `Only ${maxItemCount} values can be added.`, + itemComparer: (choice, item) => (choice === item), fuseOptions: { includeScore: true, },