Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
119
rated 0 times [  122] [ 3]  / answers: 1 / hits: 15886  / 9 Years ago, thu, september 24, 2015, 12:00:00

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?


More From » jquery

 Answers
17

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


[#64945] Monday, September 21, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaelyn

Total Points: 619
Total Questions: 102
Total Answers: 104

Location: Honduras
Member since Sun, Dec 26, 2021
2 Years ago
;