Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 custom dataAdapter without AMD

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.

like image 554
Thanasis Ioannidis Avatar asked Oct 01 '15 09:10

Thanasis Ioannidis


2 Answers

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 :)

like image 60
Gili Avatar answered Oct 02 '22 13:10

Gili


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
}]);
like image 42
Kevin Brown-Silva Avatar answered Oct 02 '22 13:10

Kevin Brown-Silva