在Select2版本4.x中为数据适配器添加装饰器

Add decorator to data adapter in Select2 version 4.x

本文关键字:添加 适配器 数据 版本 Select2      更新时间:2023-09-26

我想为我的自定义Select2数据适配器支持MaximumInputLength装饰器。在我的自定义数据适配器中,Utils.Decorate()调用不做任何事情。

看这个要点,我可以在我初始化select2()的相同位置调用Decorator函数,但这似乎很讨厌,而不是DRY,因为我想初始化许多这些Select元素。

为了使MyDataAdapter的所有实例的输入最小,是否有可能从适配器本身修饰该适配器?有更好的方法吗?

My select2() call:

$('select').select2({
    dataAdapter: MyDataAdapter,
    minimumInputLength: 2
});

MyDataAdapter (sans dependencies):

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;
});

您将注意到,在要点中,他们对装饰适配器的调用看起来像

var dropdownAdapter = Utils.Decorate(
  Utils.Decorate(
    DropdownAdapter,
    DropdownSearch
  ),
  AttachContainer
);

然后在初始化Select2时继续使用dropdownAdapter。这是因为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);
});

之前,你的主要问题是你没有使用从Utils.Decorate返回的类。但是你会遇到的另一个问题是,它只是不会工作,这是因为你重写了query方法后,它已经被装饰。