The Proxy Pattern
There are times when it is necessary for us to control the access and context behind an object, and this is where the Proxy pattern can be useful.
It can help us control when an expensive object should be instantiated, provide advanced ways to reference the object, or modify the object to function a particular way in specific contexts.
In jQuery core, a jQuery.proxy()
method exists that accepts as input a function and returns a new one that
will always have a specific context. This ensures that the value of
this within a function is the value we
expect.
An example of where this is useful is when we’re making use of
timers within a click event handler.
Imagine we have the following handler prior to adding any timers:
$("button").on("click",function(){// Within this function, "this" refers to the element that was clicked$(this).addClass("active");});
If we wished to add a hard delay before the active class was added, we
could use setTimeout() to achieve this. Unfortunately
there is a small problem with this solution: whatever function is passed
to setTimeout() will have a different
value for this within that function. It
will instead refer to the window
object, which is not what we desire.
$("button").on("click",function(){setTimeout(function(){// "this" doesn't refer to our element!// It refers to window$(this).addClass("active");});});
To work around this problem, we can use jQuery.proxy() to implement a type of proxy pattern. By calling ...