In the previous section, we learned how to create an object using the Singleton pattern. Now we will discover how to access it from other objects in a web application. The AjaxUpdater object can be used in any other object throughout your web application, all we need to do is import the file.
Because the object instantiates itself, it is usable from the moment the file is loaded and can be called directly by name from any object that is loaded into the same page. Using a Singleton object method and property, such as the AjaxUpdater, is extremely easy. The following line of code makes an XHR and sets a callback method, which waits for the response from the server through the Ajax engine:
AjaxUpdater.Update("GET" , "services/accordion.xml", Accordion.display);
This method is called by name because it resides in the same page as the object that is making the request. The only code we would need to write at this point is the callback method that handles the response. You can refer to Listing 14.3 to get an idea of how this method would be written, although if you were to write a custom callback method, you would be doing so because you want to parse a custom response. Therefore, you would write additional code in the method to handle any custom actions you would like to accomplish. As an example, I have included a snippet of code in Listing 14.5 that we will cover in Chapter 16, "The Observer Pattern", to show you how a custom response handler might look and how you can get started parsing the response.
Listing 14.5. Accessing a Method in a Singleton Object
As you can see, the AjaxUpdater might be a small object, but it packs a lot of power and is the perfect candidate for the Singleton pattern. In this chapter, the Singleton pattern made the AjaxUpdater accessible from anywhere in the application and gave us a consistent reference to the object so that we did not have to worry about having the current information. Separating important pieces of functionality into separate objects provides us with layers of abstraction that keeps our code clean and easily scalable. Now that we have covered this simple design pattern, let's move on to discover a few more complex patterns that will help us optimize the code in our Ajax applications.