jQuery.proxy()用法 [英] jQuery.proxy() usage

查看:108
本文介绍了jQuery.proxy()用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读关于 jQuery.proxy() 。它看起来很有希望,但我想知道在什么情况下这是最好用的。任何人都可以启发我吗?

I was reading the api about jQuery.proxy(). It looks promising but I was wondering in what situation is this best use. Can anyone enlighten me?

推荐答案

当你想要一个具有这个绑定到特定对象的值。例如,在回调中,例如事件处理程序,AJAX回调,超时,间隔,自定义对象等。

When you want a function that has the this value bound to a specific object. For example, in callbacks such as event handlers, AJAX callbacks, timeouts, intervals, custom objects, etc.

这只是一个可能出现的情况的制造示例有用。假设有一个具有属性名称的 Person 对象。它还链接到文本输入元素,每当输入值更改时,此person对象中的名称也会更新。

This is just a manufactured example of a situation where it might be useful. Assuming there is a Person object which has a property name. It is also linked to a text input element, and whenever the input value changes, the name in this person object gets updated too.

function Person(el) {
    this.name = '';

    $(el).change(function(event) {
        // Want to update this.name of the Person object,
        // but can't because this here refers to the element
        // that triggered the change event.
    });
}

我们经常使用的一个解决方案是将此上下文存储在变量中在回调函数中使用它,例如:

One solution that we often use is to store the this context in a variable and use that inside the callback function such as:

function Person(el) {
    this.name = '';

    var self = this; // store reference to this

    $(el).change(function(event) {
        self.name = this.value; // captures self in a closure
    });
}

或者,我们可以使用 jQuery.proxy 这里引用 this 引用Person的对象而不是触发事件的元素。

Alternatively, we could have used jQuery.proxy here so the reference to this refers to the object of Person instead of the element that triggered the event.

function Person(el) {
    this.name = '';

    $(el).change(jQuery.proxy(function(event) {
        this.name = event.target.value;
    }, this));
}

请注意,此功能已标准化为ECMAScript 5,现在包含 bind prototypejs 借来的方法已经可用一些浏览器。

Note that this feature has been standardized into ECMAScript 5 which now includes the bind method borrowed from prototypejs and is already available on some browsers.

function Person(el) {
    this.name = '';

    $(el).change(function(event) {
        this.name = event.target.value;
    }.bind(this)); // we're binding the function to the object of person
}

这篇关于jQuery.proxy()用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆