Select2 4 custom data adapter

PowerGamer picture PowerGamer · Aug 4, 2015 · Viewed 12.3k times · Source

I am trying to create a custom data adapter according to an example here: http://select2.github.io/announcements-4.0.html#query-to-data-adapter. How can I move the line that creates the select2 control outside the function with definition of DataAdapter (see the code below)?

<!DOCTYPE html>
<head>
    <title></title>
    <link href="select2.css" rel="stylesheet" />
    <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.js"></script>
    <script type="text/javascript" src="select2.full.js"></script>
    <script type="text/javascript">
        $.fn.select2.amd.require(
            ['select2/data/array', 'select2/utils'],
            function (ArrayData, Utils) {
                function CustomData ($element, options) {
                    CustomData.__super__.constructor.call(this, $element, options);
                }

                Utils.Extend(CustomData, ArrayData);

                CustomData.prototype.query = function (params, callback) {
                    var data = {results: []};
                    data.results.push({id: params.term, text: params.term});
                    data.results.push({id: 11, text: 'aa'});
                    data.results.push({id: 22, text: 'bb'});
                    callback(data);
                };

// Works if uncommented, but this line needs to be elsewhere (in $(document).ready()).
                //$("#my").select2({tags: true, dataAdapter: CustomData});
            });

        $(document).ready(function() {
// This line does not work here.            
            $("#my").select2({tags: true, dataAdapter: CustomData});
        });
    </script>
</head>
<body>
    <select id="my"></select>
</body>
</html>

Answer

gunthor picture gunthor · Aug 20, 2015

you define it via AMD-Pattern:

$.fn.select2.amd.define('select2/data/customAdapter',[
        'select2/data/array',
        'select2/utils'
    ],
    function (ArrayAdapter, Utils) {

        function CustomDataAdapter ($element, options) {
            CustomDataAdapter.__super__.constructor.call(this, $element, options);
        }
        Utils.Extend(CustomDataAdapter, ArrayAdapter);

        CustomDataAdapter.prototype.current = function (callback) {

            callback(...);

        };

        return CustomDataAdapter;
    }
);

var customAdapter=$.fn.select2.amd.require('select2/data/customAdapter');

$("#my").select2({
    tags: true, 
    dataAdapter: customAdapter
});