Select2:如何让formatSelection具有特定上下文环境

3

我为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使用“正确”的上下文调用我的函数?

1个回答

1
尝试使用function.bind显式地绑定this上下文。原因是this上下文被设置为调用者的上下文(除了绑定函数),而您的函数是从选择插件内部调用的回调,因此在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
});

由于您正在使用jQuery,因此您也可以使用$.proxy

formatSelection : $.proxy(this.formatSelection,this)

哇,这比我预想的要容易得多 :) 谢谢! - a.real.human.being

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接