Home > Article > Web Front-end > Detailed examples of four usage scenarios of jquery.proxy
In fact, there are only two ways to use it, but each one is subdivided into whether to pass parameters.
Give me a piece of HTML first, which will be used for testing later:
1,jquery.proxy(function, context);
Use context as function running context (i.e. this)
2, jQuery.proxy(function, context [, additionalArguments]);
Pass parameters to function
Usage scenario: when click, To execute the function, in the given context, two parameters are passed at the same time. If an event is required, it can be used as the third parameter of the function.
Note: If proxy is not applicable in the function execution environment, the context will be the current clicked object. Now that other contexts are specified, they have nothing to do with the current clicked object.
var me = { /* I'm a dog */ type: "dog", /* Note that event comes *after* one and two */ test: function(one, two, event) { $("#log") /* `one` 是第一个附加参数,与对象`you`对应 */ .append( "<h3>Hello " + one.type + ":</h3>" ) /* `two` 是第二个附加参数,与对象`they`对应 */ .append( "and they are " + two.type + ".<br>" ) /* `this` 是上下文,与普通对象`me`对应 */ .append( "I am a " + this.type + ", " ) /* 事件类型是点击"click" */ .append( "Thanks for " + event.type + "ing " ) /* `event.target`是被点击元素,类型是按钮button */ .append( "the " + event.target.type + "." ); } }; var you = { type: "cat" }; var they = { type: "fish" }; /* 一共4个参数:第一个是function,第二个是context,第三、四是参数 */ var proxy = $.proxy( me.test, me, you, they ); $("#test").on( "click", proxy ); /* 运行结果: Hello cat: and they are fish. I am a dog, Thanks for clicking the submit. */
In this case, click is just equivalent to a trigger button, and the function executed after triggering has nothing to do with click.
3, jQuery.proxy(context, name);
Usage scenario: context is a PlainObject, and name is its method. It is executed when click, but the execution context of the test function is obj, not $("#test")
var obj = { name: "John", test: function() { console.log(this); $("#log").append( this.name ); $("#test").off("click", obj.test); } }; $("#test").on( "click", jQuery.proxy( obj, "test" ) );//在click时执行,但又 不是click的上下文
Result analysis: After binding the click event, the first time it is executed, The binding is removed.
After removal, there is no click event on the button, so if you click the button again, there will be no reaction.
4, jQuery.proxy(context, name [, additionalArguments]);
A question:
I want to ask you a question,
jQuery.proxy (context, function, params);
and
function.call(context, params);
The above is the detailed content of Detailed examples of four usage scenarios of jquery.proxy. For more information, please follow other related articles on the PHP Chinese website!