Example 1 — Function + Context
Lock this to your object when the handler runs.
var me = {
type: "zombie",
test: function (event) {
$("#out").text("Hello " + this.type);
// element is still available:
// event.target
}
};
$("#test").on("click", $.proxy(me.test, me));
How It Works
- Method.
me.test expects this to be me. - Proxy.
$.proxy(me.test, me) returns a wrapped function. - Click. jQuery calls the wrapper;
this stays me.
Example 2 — Context + Method Name
Pass the object and the method name as a string.
var obj = {
name: "John",
test: function () {
$("#out").text(this.name);
}
};
$("#test").on("click", $.proxy(obj, "test"));
How It Works
- Lookup. jQuery reads
obj["test"]. - Bind. That function is locked to
obj as this. - Click. Handler prints
obj.name.
Example 3 — Extra Arguments
Prepend values; the event object still arrives last.
var me = {
type: "dog",
test: function (one, two, event) {
$("#out").text(
one.type + " / " + this.type + " / " + two.type + " / " + event.type
);
}
};
var you = { type: "cat" };
var they = { type: "fish" };
$("#test").on("click", $.proxy(me.test, me, you, they));
How It Works
- Extras.
you and they are bound as the first two args. - Context.
this is still me ("dog"). - Event. jQuery appends the event object after the extras.