将装饰器添加到Select2版本4.x中的数据适配器

Ben*_*ith 2 javascript jquery-select2

我想支持MaximumInputLength我的自定义Select2 数据适配器的装饰.在我的自定义数据适配器中,Utils.Decorate()调用不执行任何操作.

看看这个要点,我可以在我初始化的同一个地方调用Decorator函数select2(),但这看起来很蹩脚而不是DRY,因为我想初始化许多这些Select元素.

为了为MyDataAdapter的所有实例启用最小输入,是否可以从适配器本身装饰该适配器?有一个更好的方法吗?

我的select2()电话:

$('select').select2({
    dataAdapter: MyDataAdapter,
    minimumInputLength: 2
});
Run Code Online (Sandbox Code Playgroud)

MyDataAdapter (没有依赖):

define([...], function(Utils, MinimumInputLength, ArrayAdapter){

    function MyDataAdapter($element, options) {
        this.$element = $element;
        this.options = options;
        MyDataAdapter.__super__.constructor.call(this, $element, options);
    }

    Utils.Extend(MyDataAdapter, ArrayAdapter);
    Utils.Decorate(MyDataAdapter, MinimumInputLength); <-- does nothing

    MyDataAdapter.prototype.query = function(params, callback) {
        console.log('query!');
    };

    return MyDataAdapter;

});
Run Code Online (Sandbox Code Playgroud)

Kev*_*own 8

你会在gist中注意到他们调用装饰他们的适配器的样子

var dropdownAdapter = Utils.Decorate(
  Utils.Decorate(
    DropdownAdapter,
    DropdownSearch
  ),
  AttachContainer
);
Run Code Online (Sandbox Code Playgroud)

然后他们dropdownAdapter在初始化Select2时继续使用.这是因为Utils.Decorate 返回装饰类而不是就地装饰它.您还会注意到,在创建了装饰器和适配器之后,它会执行此操作.

因此Utils.Decorate,您应该在最后调用它,而不是在适配器的中间调用.当您返回完成的适配器时,或者在您返回之前.

define([...], function(Utils, MinimumInputLength, ArrayAdapter){    
    function MyDataAdapter($element, options) {
        this.$element = $element;
        this.options = options;
        MyDataAdapter.__super__.constructor.call(this, $element, options);
    }

    // Always extend after making the constructor
    Utils.Extend(MyDataAdapter, ArrayAdapter);

    MyDataAdapter.prototype.query = function(params, callback) {
        console.log('query!');
    };

    // Decorate after the adapter is built
    return Utils.Decorate(MyDataAdapter, MinimumInputLength);
});
Run Code Online (Sandbox Code Playgroud)

在您的主要问题之前,您没有使用返回的类Utils.Decorate.但是你要碰到的另一个问题是它不会起作用,这是因为你query在装饰后重写了这个方法.