From 4431a0ec237c818f7af71e6c962ec5db1da60263 Mon Sep 17 00:00:00 2001 From: Josh Johnson Date: Tue, 9 Oct 2018 12:43:25 +0100 Subject: [PATCH] Use deepmerge lib + store all defaults in DEFAULT_CONFIG --- package.json | 1 + src/scripts/choices.js | 24 ++++-------------------- src/scripts/constants.js | 4 +++- 3 files changed, 8 insertions(+), 21 deletions(-) diff --git a/package.json b/package.json index 6896f9d..c9f733a 100644 --- a/package.json +++ b/package.json @@ -77,6 +77,7 @@ "classnames": "^2.2.5", "core-js": "^2.5.6", "custom-event-polyfill": "^0.3.0", + "deepmerge": "^2.2.1", "fuse.js": "^3.1.0", "opn": "^5.1.0", "redux": "^3.3.1" diff --git a/src/scripts/choices.js b/src/scripts/choices.js index 05a4e4e..4c30d46 100644 --- a/src/scripts/choices.js +++ b/src/scripts/choices.js @@ -1,4 +1,5 @@ import Fuse from 'fuse.js'; +import merge from 'deepmerge'; import './lib/polyfills'; import Store from './store/store'; @@ -10,12 +11,7 @@ import { WrappedInput, WrappedSelect, } from './components'; -import { - DEFAULT_CONFIG, - DEFAULT_CLASSNAMES, - EVENTS, - KEY_CODES, -} from './constants'; +import { DEFAULT_CONFIG, EVENTS, KEY_CODES } from './constants'; import { TEMPLATES } from './templates'; import { addChoice, @@ -33,7 +29,6 @@ import { isType, strToEl, extend, - sortByAlpha, sortByScore, generateId, findAncestorByAttrName, @@ -60,7 +55,7 @@ class Choices { } } - this.config = Choices._generateConfig(userConfig); + this.config = merge.all([DEFAULT_CONFIG, Choices.userDefaults, userConfig]); if (!['auto', 'always'].includes(this.config.renderSelectedChoices)) { this.config.renderSelectedChoices = 'auto'; @@ -173,6 +168,7 @@ class Choices { this._store.subscribe(this._render); this._render(); this._addEventListeners(); + this.initialised = true; const { callbackOnInit } = this.config; @@ -2029,18 +2025,6 @@ class Choices { ); } - static _generateConfig(userConfig) { - const defaultConfig = { - ...DEFAULT_CONFIG, - items: [], - choices: [], - classNames: DEFAULT_CLASSNAMES, - sortFn: sortByAlpha, - }; - - return extend(defaultConfig, Choices.userDefaults, userConfig); - } - _generatePlaceholderValue() { if (this._isSelectOneElement) { return false; diff --git a/src/scripts/constants.js b/src/scripts/constants.js index f750fd3..2ef4e87 100644 --- a/src/scripts/constants.js +++ b/src/scripts/constants.js @@ -1,4 +1,4 @@ -import { stripHTML } from './lib/utils'; +import { stripHTML, sortByAlpha } from './lib/utils'; export const DEFAULT_CLASSNAMES = { containerOuter: 'choices', @@ -52,6 +52,7 @@ export const DEFAULT_CONFIG = { regexFilter: null, shouldSort: true, shouldSortItems: false, + sortFn: sortByAlpha, placeholder: true, placeholderValue: null, searchPlaceholderValue: null, @@ -71,6 +72,7 @@ export const DEFAULT_CONFIG = { }, callbackOnInit: null, callbackOnCreateTemplates: null, + classNames: DEFAULT_CLASSNAMES, }; export const EVENTS = {