Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
891 views
in Technique[技术] by (71.8m points)

javascript - How to enable infinite scrolling in select2 4.0 without ajax

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...