您的位置:首页 > Web前端 > JQuery

jquery.proxy的四种使用场景及疑问

2014-06-04 19:29 330 查看
作者:zccst

其实只有两种使用方式,只不过每一种又细分是否传参。

先给一段HTML,后面会用来测试:

<p><button id="test">Test</button></p>
<p id="log"></p>


1,jQuery.proxy(function, context);

使用context作为function运行上下文(即this)

2,jQuery.proxy(function, context [, additionalArguments]);

传递参数给function

使用场景:click时,执行function,在给定的context里,同时传递两个参数,如果需要event,则可以作为function第三个参数。

注意:function执行的环境如果不适用proxy,则context会是当前点击对象,现在指定了其他的上下文,已经跟当前点击对象没有一点关系了。

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.
*/


在这种情况下,click仅仅相当于一个触发按钮,触发后执行的函数,跟click一点关系都没有了。

3,jQuery.proxy(context, name);

使用场景:context是一个PlainObject,name是其方法。在click时执行,但test函数执行的上下文是obj,不是$("#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的上下文


结果分析:在绑定点击事件后,第一次执行时,就把该绑定去除了。

去除之后,button上已经没有点击事件,所以再点击按钮,也不会有任何反应了。

4,jQuery.proxy(context, name [, additionalArguments]);

一个疑问:

请教大家一个问题,
jQuery.proxy(context, function, params);

function.call(context,params);
区别是什么?
我遇到一个问题是用proxy没反应,用call时就有反应。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: