In many instances, you may need to persistently store small amounts of personalization information for a user. One of the features available within the OpenSocial gadgets JavaScript libraries provides a facility to help you do just that.
To integrate this feature, you need to take a few steps:
Within the
ModulePrefs
node of the gadget spec file, add aRequire
element includingsetprefs
to enable theflash
JavaScript library.Include:
<Require feature="setprefs"/>
Add a
UserPref
node with the value matching the user preference element you wish to persistently store.When you wish to set a new user preference, you will need to call the
set()
method of thegadgets.Prefs
object.Method call:
set(...);
There are several methods available that provide user preference getting and setting abilities, listed in Table 4-3.
Table 4-3. User preference methods
<Module> <ModulePrefs> <Require feature="setprefs" /> </ModulePrefs> <UserPref name="count" default_value="0" datatype="hidden" /> <Content view="canvas"> <![CDATA[ <div id="myNum">0</div> <button onclick="increment();">Add 1</button> <button onclick="decrement();">Subtract 1</button> <script type="text/javascript"> var outputContainer = document.getElementById('myNum'); //set prefs variable var prefs = new gadgets.Prefs(); function increment(){ //capture current UserPref value var count = prefs.getInt("count"); //set new user pref and increment counter prefs.set("count", count + 1); outputContainer.innerHTML = count + 1; } function decrement(){ //capture current UserPref value var count = prefs.getInt("count"); //set new user pref and decrement counter prefs.set("count", count - 1); outputContainer.innerHTML = count - 1; } </script> ]]> </Content> </Module>
Note
The full code for this sample is available at https://github.com/jcleblanc/programming-social-applications/blob/master/chapter_4/saving_state_with_userprefs.xml.
The preceding example demonstrates the process by which you get and
set user preference variables. We create buttons to call our increment and
decrement functions and, once hit, each function captures the current user
preference count
variable and either
increments or decrements it.
Get Programming Social Applications now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.