Javascript Select2:获取formatSelection以具有特定上下文

Javascript Select2:获取formatSelection以具有特定上下文,javascript,jquery,jquery-select2,Javascript,Jquery,Jquery Select2,我为Select2制作了一个非常简单的包装器(这确实很有帮助),但在使用formatSelection字段时遇到了困难。例如,我通过包装器初始化Select2,如下所示: this.elem.select2({ allowClear : options.allowClear ? true : false, placeholder : options.placeholder ? options.placeholder : undefined, createSearchCho

我为Select2制作了一个非常简单的包装器(这确实很有帮助),但在使用
formatSelection
字段时遇到了困难。例如,我通过包装器初始化Select2,如下所示:

this.elem.select2({
    allowClear : options.allowClear ? true : false,
    placeholder : options.placeholder ? options.placeholder : undefined,
    createSearchChoice : !options.preventNew ? this.newEntry : undefined,
    formatSelection : this.formatSelection,
    data : this.data
});
但是,问题是,当调用
this.formatSelection
时(实际上),
this
引用的是Select2实例,而不是我的包装器。有人知道如何让select2使用“正确”的上下文调用我的函数吗?

尝试使用绑定
上下文的明确性。原因是
上下文被设置为调用方的上下文(绑定函数除外),并且您的函数是从select插件中调用的回调函数,因此使用
formatSelection
的上下文自然是
select2
的上下文,而不是您的插件实例

this.elem.select2({
    allowClear : options.allowClear ? true : false,
    placeholder : options.placeholder ? options.placeholder : undefined,
    createSearchChoice : !options.preventNew ? this.newEntry : undefined,
    formatSelection : this.formatSelection.bind(this), //<-- here
    data : this.data
});

嗯,这比我想象的要容易得多:)谢谢!
formatSelection : $.proxy(this.formatSelection,this)