Select2 custom dataAdapter without AMD
Asked Answered
A

2

8

I want to create a custom dataAdapter for select2 but the examples I see online all make use of AMD. We don't use AMD in our projects. How can I create my custom dataAdapter? A plain object that implements current and query methods is not enough.

Anabelanabella answered 1/10, 2015 at 9:53 Comment(0)
O
5

It turns out you can almost completely avoid the use of AMD. The following works for me with select2 version 4.0.10:

const ArrayAdapter = $.fn.select2.amd.require("select2/data/array");

class DataAdapter extends ArrayAdapter
{
    constructor($element, options)
    {
        super($element, options);
    }

    query(params, callback)
    {
        console.log("params: " + JSON.stringify(params));
    }
}

$("#my-combo-box").select2(
    {
        dataAdapter: DataAdapter
    }
);

You can ever go as far as accessing $.fn.select2.amd.require._defined["select2/data/array"] instead of invoking amd.require() but there is probably no point going this far :)

Olli answered 9/9, 2019 at 16:17 Comment(2)
I've been looking for this answer for ages. Thank you! So much cleaner than anything else I've seen.Myxoma
@NickBrunt hey buddy could you share a simple example of how you accomplished this? I'm trying to customize the dropdown content with the Dropdown decorator, but having hard times with it :(. Thanks in advance.Binge
G
1

Select2 has a built-in AMD loader that it uses for loading plugins and adapters, so you would need to use that to build out your custom data adapter.

You can find examples of customized data adapters at Add decorator to data adapter in Select2 version 4.x

Instead of calling define directly, you would need to use the method provided by Select2 in jQuery.fn.select2.amd. So something like

define('something/awesome', ['select2/data/array', function (ArrayAdapter) {
  // Use the array adapter
}]);

would become

jQuery.fn.select2.amd.define('something/awesome', ['select2/data/array', function (ArrayAdapter) {
  // Use the array adapter
}]);
Glutamine answered 2/10, 2015 at 17:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.