Skip to content

Commit

Permalink
[MAJOR] Remove .ajax and allow async function for .setChoices (#701)
Browse files Browse the repository at this point in the history
* WIP: remove ajax

* copy #700

* remove ajax, add fetchChoices

* extend setChoices

* update README
  • Loading branch information
tinovyatkin authored and jshjohnson committed Oct 29, 2019
1 parent 1f5192b commit e3cc6ea
Show file tree
Hide file tree
Showing 9 changed files with 635 additions and 429 deletions.
63 changes: 19 additions & 44 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -863,7 +863,9 @@ choices.disable();
**Input types affected:** `select-one`, `select-multiple`
**Usage:** Set choices of select input via an array of objects, a value name and a label name. This behaves the same as passing items via the `choices` option but can be called after initialising Choices. This can also be used to add groups of choices (see example 2); Optionally pass a true `replaceChoices` value to remove any existing choices. Optionally pass a `customProperties` object to add additional data to your choices (useful when searching/filtering etc). Passing an empty array as the first parameter, and a true `replaceChoices` is the same as calling `clearChoices` (see below).
**Usage:** Set choices of select input via an array of objects (or function that returns array of object or promise of it), a value field name and a label field name.
This behaves the similar as passing items via the `choices` option but can be called after initialising Choices. This can also be used to add groups of choices (see example 3); Optionally pass a true `replaceChoices` value to remove any existing choices. Optionally pass a `customProperties` object to add additional data to your choices (useful when searching/filtering etc). Passing an empty array as the first parameter, and a true `replaceChoices` is the same as calling `clearChoices` (see below).
**Example 1:**
Expand All @@ -887,6 +889,22 @@ example.setChoices(
```js
const example = new Choices(element);

// Passing a function that returns Promise of choices
example.setChoices(async () => {
try {
const items = await fetch('/items');
return items.json();
} catch (err) {
console.error(err);
}
});
```
**Example 3:**
```js
const example = new Choices(element);

example.setChoices(
[
{
Expand Down Expand Up @@ -1009,49 +1027,6 @@ example.setChoiceByValue('Two'); // Choice with value of 'Two' has now been sele
**Usage:** Enables input to accept new values/select further choices.
### ajax(fn);
**Input types affected:** `select-one`, `select-multiple`
**Usage:** Populate choices/groups via a callback.
**Example:**
```js
var example = new Choices(element);

example.ajax(function(callback) {
fetch(url)
.then(function(response) {
response.json().then(function(data) {
callback(data, 'value', 'label');
});
})
.catch(function(error) {
console.log(error);
});
});
```
**Example 2:**
If your structure differs from `data.value` and `data.key` structure you can write your own `key` and `value` into the `callback` function. This could be useful when you don't want to transform the given response.
```js
const example = new Choices(element);

example.ajax(function(callback) {
fetch(url)
.then(function(response) {
response.json().then(function(data) {
callback(data, 'data.key', 'data.value');
});
})
.catch(function(error) {
console.log(error);
});
});
```
## Browser compatibility
Choices is compiled using [Babel](https://babeljs.io/) to enable support for [ES5 browsers](http://caniuse.com/#feat=es5). If you need to support a browser that does not support one of the features listed below, I suggest including a polyfill from the very good [polyfill.io](https://cdn.polyfill.io/v2/docs/):
Expand Down
77 changes: 35 additions & 42 deletions public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,7 @@ <h2>Single select input</h2>
</select>

<label for="choices-single-remove-xhr"
>Options from remote source (XHR) &amp; remove button</label
>Options from remote source (Fetch API) &amp; remove button</label
>
<select
class="form-control"
Expand Down Expand Up @@ -627,17 +627,17 @@ <h2>Form interaction</h2>
placeholder: true,
placeholderValue: 'Pick an Strokes record',
maxItemCount: 5,
}).ajax(function(callback) {
fetch(
}).setChoices(function() {
return fetch(
'https://api.discogs.com/artists/55980/releases?token=QBRmstCkwXEvCjTclCpumbtNwvVkEzGAdELXyRyW',
)
.then(function(response) {
response.json().then(function(data) {
callback(data.releases, 'title', 'title');
});
return response.json();
})
.catch(function(error) {
console.error(error);
.then(function(data) {
return data.releases.map(function(release) {
return { value: release.title, label: release.title };
});
});
});

Expand Down Expand Up @@ -685,46 +685,39 @@ <h2>Form interaction</h2>

var singleFetch = new Choices('#choices-single-remote-fetch', {
searchPlaceholderValue: 'Search for an Arctic Monkeys record',
}).ajax(function(callback) {
fetch(
'https://api.discogs.com/artists/391170/releases?token=QBRmstCkwXEvCjTclCpumbtNwvVkEzGAdELXyRyW',
)
.then(function(response) {
response.json().then(function(data) {
callback(data.releases, 'title', 'title');
singleFetch.setChoiceByValue('Fake Tales Of San Francisco');
})
.setChoices(function() {
return fetch(
'https://api.discogs.com/artists/391170/releases?token=QBRmstCkwXEvCjTclCpumbtNwvVkEzGAdELXyRyW',
)
.then(function(response) {
return response.json();
})
.then(function(data) {
return data.releases.map(function(release) {
return { label: release.title, value: release.title };
});
});
})
.catch(function(error) {
console.error(error);
});
});
})
.then(function(instance) {
instance.setChoiceByValue('Fake Tales Of San Francisco');
});

var singleXhrRemove = new Choices('#choices-single-remove-xhr', {
removeItemButton: true,
searchPlaceholderValue: "Search for a Smiths' record",
}).ajax(function(callback) {
var request = new XMLHttpRequest();
request.open(
'get',
}).setChoices(function(callback) {
return fetch(
'https://api.discogs.com/artists/83080/releases?token=QBRmstCkwXEvCjTclCpumbtNwvVkEzGAdELXyRyW',
true,
);
request.onreadystatechange = function() {
var status;
var data;
if (request.readyState === 4) {
status = request.status;
if (status === 200) {
data = JSON.parse(request.responseText);
callback(data.releases, 'title', 'title');
singleXhrRemove.setChoiceByValue('How Soon Is Now?');
} else {
console.error(status);
}
}
};
request.send();
)
.then(function(res) {
return res.json();
})
.then(function(data) {
return data.releases.map(function(release) {
return { label: release.title, value: release.title };
});
});
});

var genericExamples = new Choices('[data-trigger]', {
Expand Down
Loading

0 comments on commit e3cc6ea

Please sign in to comment.