How to enable infinite scrolling in select2 4.0 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
Expanding on this answer to show how to retain the search functionality that comes with select2. Thanks Paperback Writer!
Also referenced this example of how to achieve infinite scrolling using a client side data source, with select2 version 3.4.5.
This example uses the oringal options in a select tag to build the list instead of item array which is what was called for in my situation.
function contains(str1, str2) {
return new RegExp(str2, "i").test(str1);
}
CustomData.prototype.query = function (params, callback) {
if (!("page" in params)) {
params.page = 1;
}
var pageSize = 50;
var results = this.$element.children().map(function(i, elem) {
if (contains(elem.innerText, params.term)) {
return {
id:[elem.innerText, i].join(""),
text:elem.innerText
};
}
});
callback({
results:results.slice((params.page - 1) * pageSize, params.page * pageSize),
pagination:{
more:results.length >= params.page * pageSize
}
});
};
Here is a jsfiddle