39

I've come across the notion of 'Proxy Pattern' today on jQuery.com, but could not make anything of it. Apparently it is of great use, but I do not understand the idea at all, it sounds alien to me. Could someone please explain it to me in simple terms, "as if I were a 3 year old"?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Andrei Oniga
  • 8,219
  • 15
  • 52
  • 89
  • 4
    lmgtfy: http://mark.biek.org/blog/2010/04/the-proxy-pattern-in-javascript/. Maybe that helps? – home Sep 11 '11 at 16:51
  • @home: I read that post already but still don't understand the idea. – Andrei Oniga Sep 11 '11 at 17:08
  • I voted for close because it is an exact duplicate other another question as @yoda pointed out. – home Sep 11 '11 at 17:20
  • @home: You might want to read a post thoroughly first. Here's what Reigel wrote that post: "I was wondering in what situation is this best use". How do you find that I asked the same thing? Is it just my imagination, or did I ask "what is this?" instead? I'm not interested in how this "idea" would be put to good/better use, but wish to understand the concept itself. Consider the distinction! – Andrei Oniga Sep 11 '11 at 17:30
  • @Andrei Oniga: I read the first answer and thought it does explain the concept based on an good example. Does this not work for you? If your interested in the proxy pattern itself (no, it is not JavaScript specific), did you look at [WikiPedia](http://en.wikipedia.org/wiki/Proxy_pattern)? – home Sep 11 '11 at 17:38
  • @Andrei Oniga the answers you'll get will be similar to those already answered before in other topics. `$.proxy` is used to pass local resources into methods that aren't local. Can't find a reason to do that? Read my first comment. If you still don't understand the benefits / reasons for it's existence, maybe you lack on some basic javascript knowledge / experience with it. – yoda Sep 11 '11 at 17:42
  • 3
    I must say that i totally **fail** to see the connection between this question and the one linked above, aside from the use of the same word "proxy". The post above talks about binding a new context to function execution. Which is done by calling `proxy()` method in jQuery. Proxy Pattern, while may be mildly related and used in `proxy()` method, is a totally different thing. Additionally, nowhere the OP mentioned that he is interested in some sort of specific jQuery solution, aside from saying where he got the idea from. It isn't even tagged jQuery anymore. – ZenMaster Sep 11 '11 at 17:43
  • Did you ask about the $.proxy method from jQuery or about the pattern? Anyway, take a look at my answer. – hasser Dec 21 '11 at 14:59

5 Answers5

47

Imagine you have site with many ajax requests. There is a change in design. Now before each request you want to display some custom loading gif. You neeed to change all the code where there is an ajax request or you can use proxy pattern.

var proxied = jQuery.ajax; // Preserving original function
jQuery.ajax = function() { 
    jQuery("#loading").dialog({modal: true});
    return proxied.apply(this, arguments);
}
pylover
  • 7,670
  • 8
  • 51
  • 73
Ivan
  • 2,262
  • 1
  • 18
  • 16
  • 3
    ...or you could just add an [`ajaxStart`](http://api.jquery.com/ajaxStart) handler... – icktoofay Sep 12 '11 at 02:03
  • 2
    I never use jQuery or any other framework directly .. Always there is an adapter which wrap framework code, so I can handle such changes. Goal of code above was do give an example usage of proxy pattern – Ivan Sep 12 '11 at 07:04
  • 3
    I realize that you were trying to demonstrate the "proxy pattern" but I was just saying that it might be a bad example because the library already has a better way of accomplishing what you had in your example. – icktoofay Sep 13 '11 at 00:35
31

In Javascript Patterns book, Stoyan Stefanov describes this pattern as so:

In the proxy pattern, one object acts as an interface to another object. The proxy sits between the client of an object and the object itself and protects the access to that object.

This pattern might look like an overhead but it's useful for perfomance purposes. The proxy servers play a guardian role for the object (also called "real subject") and tries to make this object do as little work as possible.

A real world example

The proxy pattern is useful when the real subject does something expensive. In web applications, one of the most expensive operations you can do is a network request, so it makes sense to combine HTTP requests as much as possible.

You can see an example here: http://www.jspatterns.com/book/7/proxy.html. (take a look at the source code).

You have a list of videos on the page. When the user clicks a video title, the area below the title expands to show more information about the video and also enables the video to be played. The detailed video information and the URL of the video are not part of the page; they need to be retrieved by making a web service call. The web service can accept multiple video IDs, so we can speed up the application by making fewer HTTP requests whenever possible and retrieving data for several videos at one time.

The videos object doesn't call the HTTP service directly but calls the proxy instead. The proxy then waits before forwarding the request. If other calls from videos come in the 50ms waiting period, they will be merged into one. A delay of 50ms is pretty much imperceptible for the user but can help combine requests and speed up the experience when clicking “toggle” and expanding more than one video at once. It also reduces the server load significantly since the web server has to handle a smaller number of requests.

Without proxy

Without proxy

Proxy

With Proxy

Proxy as a cache

As a cache

FurkanO
  • 7,100
  • 5
  • 25
  • 36
hasser
  • 1,066
  • 1
  • 13
  • 24
4

In general - Proxy Pattern comes to control access to a resource. By doing so it can solve several potential issues:

  1. prevent incorrect or malicious use of the resource
  2. prevent/control access to a resource that is too expensive to create

jQuery use the term rather loosely, but their idea is that you override/hide the existing method (in their example jQuery.fn.setArray) while adding more functionality to it.

(function() { // envelop everyting in anonymous immediately called function 
  var proxied = jQuery.fn.setArray; // save current method
  jQuery.fn.setArray = function() { // override the method
    console.log(this, arguments); // add functionality
    return proxied.apply(this, arguments); // call original method and return 
                                           // its result
  };
})();
ZenMaster
  • 12,363
  • 5
  • 36
  • 59
  • Sorry if i sound noobish but why is the anonymous function definition as a whole, enclosed in parenthesis and then invoked like another function? – NishM May 15 '15 at 05:15
  • 1
    @NishM This is called __self-executing anonymous function__. See [here](http://markdalgleish.com/2011/03/self-executing-anonymous-functions/) for an example. – ZenMaster May 15 '15 at 14:58
0

The Proxy pattern provides a surrogate or placeholder object for another object and controls access to this other object.

In object-oriented programming, objects do the work they advertise through their interface (properties and methods). Clients of these objects expect this work to be done quickly and efficiently. However, there are situations where an object is severely constrained and cannot live up to its responsibility. Typically this occurs when there is a dependency on a remote resource (resulting in network latency) or when an object takes a long time to load.

In situations like these you apply the Proxy pattern and create a proxy object that ‘stands in’ for the original object. The Proxy forwards the request to a target object. The interface of the Proxy object is the same as the original object and clients may not even be aware they are dealing with a proxy rather than the real object.

enter image description here

Client -- In sample code: the run() function

  • calls Proxy to request an operation.

Proxy -- In sample code: GeoProxy

  • provides an interface similar to the real object

  • maintains a reference that lets the proxy access the real object

  • handles requests and forwards these to the real object

RealSubject -- In sample code: GeoCoder

  • defines the real object for which service is requested
FraZer
  • 1,685
  • 1
  • 10
  • 17
0

Here's one example of a proxy pattern used to record what listeners are being set: Why does Google +1 record my mouse movements?.

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979