Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[MAJOR] Remove .ajax and allow async function for .setChoices #701

Merged
merged 8 commits into from
Oct 29, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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