jquery.proxy in the bootstrap-typeahead.js context



我正在读取以下代码行

  items = $.isFunction(this.source) ? this.source(this.query, $.proxy(this.process, this)) : this.source

来自bootstrap-typeahead.js v2.1.0。

有人能解释一下吗
this.source(this.query, $.proxy(this.process, this))是如何工作的?

毫无疑问:
1) 我假设this.source是指(1)中定义的函数,然后?


(1)

    element.typeahead({
        minLength: 3,
        source: function () {
             // some code
        }
    });

制动:items = $.isFunction(this.source) ? this.source(this.query, $.proxy(this.process, this)) : this.source;

所以Object有一个名为source的属性this.source。看起来this.source可能是一个数组或函数。谓词函数$.isFunction(this.source)接受一个Object,如果它是一个函数,则返回true。如果是函数,则将执行this.source(this.query, $.proxy(this.process, this))

现在停止this.source(this.query, $.proxy(this.process, this))呼叫。

我们从$.isFunction(this.source)调用的结果中知道,this.source是一个函数,它需要2个参数。第一个,this.query,我猜是一个字符串。第二个,$.proxy(this.process, this))是回调函数。$.proxy接受两个参数,一个Function和一个Object/上下文,并返回一个新函数。返回的Functions上下文(this)被确保是传入的Object/context。

$.proxy看起来像这个

var proxy = function( func, context ) {
    return ( function() {
        func.apply( context, arguments );
    });
};
//build a new function and set this to window
var newFunction = proxy( someOrtherFunction, window );
//use the new function
newFunction();

您可以在此处准备更多关于$.proxy的信息:http://api.jquery.com/jQuery.proxy/

$.proxy(this.process, this)生成的新创建的Function在this.source Function中用作回调。

最新更新