Caching involves maintaining a piece of information in a store or cache to improve performance of an application. In Flash Remoting, you can create objects to hold the contents of a remote service call. This can be handy in many situations:
A cache is typically implemented as an object or an array of objects. Each object represents one item from the remote service. All items are not retrieved, but the cache is indexed in a way that each item that is placed in the cache can be easily retrieved, as in the following code snippet: // Set up the custom object that holds the product information MyCustomObject = function (productid, productname, productdesc) { this.ProductID = productid; this.ProductName = productname; this.ProductDesc = productdesc; }; // Create the cache var myCache = new Object( ); // Set the first element of the cache as a new object with descriptive fields // This can be displayed in the UI if there is no current product myCache["0"] = new MyCustomObject( 0, // ProductID "Product Name...", // ProductName "Description..."); // ProductDesc // findItem: method for the cache array to find an // item with a ProductID that matches the specified item function findItem (theArray, theItem) { for (i in theArray) { if (theArray[i].ProductID == theItem) { return true; } } return false; } // Change handler on a Tree component: user clicks an item, and the // corresponding detail page is populated my_tree.setChangeHandler("displayProduct", _root); displayProduct = function (tree) { var theNode = tree.getSelectedNode( ); var theProductId = theNode.data; if (findItem(myCache, theProductId)) { displayCacheItem(theProductId); } else { putProductInCacheAndDisplayIt(theProductId); } }; The complete functionality of the preceding example is not implemented here, but similar functionality can be found in the application built in Chapter 14. When a user clicks an item in the Tree component, the displayProduct( ) function fires off. We use a helper function, findItem( ) , to pick the item out of the cache if the item exists. If so, the displayCacheItem( ) function displays the item directly from the cache, rather than going to the remote service. If the item is not found, another function is called ( putProductInCacheAndDisplayIt( ) ), which puts the current item into the cache before displaying it. |