I am using select2
with custom data adapter. All of the data provided to select2
is generated locally in web page (so no need to use ajax). As query
method can generate a lot of results (about 5k) opening select box is quite slow.
As a remedy, I wanted to use infinite scroll. Documentation for custom data adapter says that query
method should receive page
parameter together with term
:
@param params.page The specific page that should be loaded. This is typically provided when working with remote data sets, which rely on pagination to determine what objects should be displayed.
But it does not: only term
is present. I tried to return more: true
or more: 1000
, but this didn't help. I guess this is because, by default, infinite scroll is enabled iff ajax is enabled.
I am guessing that enabling infinite scroll will involve using amd.require
, but I am not sure what to do exactly. I tried this code:
$.fn.select2.amd.require(
["select2/utils", "select2/dropdown/infiniteScroll"],
(Utils, InfiniteScroll) =>
input.data("select2").options.options.resultsAdapter =
Utils.Decorate(input.data("select2").options.options.resultsAdapter, InfiniteScroll)
)
This is coffee script, but I hope that it is readable for everyone. input
is DOM
element containing select box - I earlier did input.select2( //options )
My question is basically, how do I enable infinite scroll without ajax
?
Select2
will only enable infinite scroll, if ajax
is enabled. Fortunately we can enable it and still use our own adapter. So putting empty object into ajax
option will do the trick.
$("select").select2({
ajax: {},
dataAdapter: CustomData
});
Next, define your own data adapter. Inside it, inn query
push pagination
info into callback.
CustomData.prototype.query = function (params, callback) {
if (!("page" in params)) {
params.page = 1;
}
var data = {};
# you probably want to do some filtering, basing on params.term
data.results = items.slice((params.page - 1) * pageSize, params.page * pageSize);
data.pagination = {};
data.pagination.more = params.page * pageSize < items.length;
callback(data);
};
Here is a full fiddle