Caching 101: How the cache works in App Cloud

If you've ever worked with HTML5 Local Storage, the following should look very familiar to you:

To save a value in the cache:

bc.core.cache("name", "Adam"); // sets "name" = "Adam"

To get a value from the cache:

bc.core.cache("name"); // returns "Adam"

What about other types of data, like numbers, arrays and objects?

bc.core.cache("age", 36);
bc.core.cache("colors", ["red", "blue"]);
bc.core.cache("company", { "name": "Brightcove", "location": "Cambridge, MA" });

When you set and get values via bc.core.cache(), the data type is preserved. This is UNLIKE how localStorage works. Compare:

bc.core.cache("colors", ["red", "blue"]);
bc.core.cache("colors"); // returns ["red", "blue"]

localStorage.setItem("colors", ["red", "blue"]);
localStorage.getItem("colors"); // returns "red,blue"

In the first example above, the value of colors is preserved as an array. In the second example, the value is converted to a string when put into storage. Here's another example that clearly illustrates the difference in behavior:

bc.core.cache("name", { "first": "Adam" });
bc.core.cache("name"); // returns { "first": "Adam" }

localStorage.setItem("name", { "first": "Adam" });
localStorage.getItem("name"); // returns "[object Object]"

In the first example above, name is still an object when we retrieve it from the cache. In the second example, name is converted to "[object Object]." Boooo.

The lesson here? bc.core.cache() is a simple and effective way to save objects for later retrieval.

p.s. Get more tips and tricks (and share your own) by joining the Brightcove App Cloud discussion group on Google.