Initializing page JavaScript from the JSONCache
Launchpad has a nice feature for initialising on-page JavaScript, called the JSONCache. I recommend considering it as your first choice when writing JavaScript that needs to be initialised. The one downside is that due to bug #740208, it’s not available for users who aren’t logged in. But then, users who aren’t logged in don’t need a lot of JavaScript, because they can’t write to most of Launchpad.
I found out about the JSONCache when we were working on he sourcepackage +sharing-details pages recently. This JavaScript has model objects, but I didn’t know how we should initialise them. We considered initialising them from the page HTML. We considered using the web service. But it turned out there’s already a great facility for this: the JSON cache.
If you’ve hacked on Launchpad’s HTML, you probably already know that every you can get LP.cache.context and LP.cache.me from any Launchpad page. These come for free, but with a little more work, you can get any object you need:
cache = IJSONRequestCache(self.request)
cache.objects.update({
'productseries': self.context.productseries,
'upstream_branch': self.upstream_branch,
'product': self.product,
})
These entries will then appear in the LP.cache with the names specified in the dict.
However, they are provided as plain JavaScript mappings, unlike the values returned by lp.client.Launchpad. You can use convert_cache to create a copy of the cache containing lp.client.Entry values. This allows you to intermix values from the lp.cache and the web service freely.
convert_cache currently lives in translations/javascript/sourcepackage_sharing_details.js, but should probably be moved into lp.client.
One extension I’d love to see would be a way to retrieve an updated copy of just the JSONRequestCache for a page. That way, we could reduce our number of round-trips, and also be confident that everything was up-to-date.
July 15th, 2011 at 10:51 pm
[…] to refresh all the client-side representation of objects related to a page in one […]
August 5th, 2011 at 2:00 pm
[…] recently posted about Initializing page JavaScript from the JSONCache. Now I’m pleased to announce that you can also get updated copies of the IJSONRequestCache, […]