Enyo Daily #1 - Preferences
I'm planning to try a new thing here. I'm relatively active in the Palm Dev Forums and have pulled together a list of topics that seem to be relatively common. So, I'm hoping to do a daily (maybe, perhaps every few days ...) post on how to solve those common issues.[[MORE]]
To start, I'm going to cover how to store preferences using the system service. The enyo tutorial covers this briefly but unfortunately inaccurately right now.
The low level approach is to call the system service directly.
// define the service in the components block
{name: "preferencesService", kind: "enyo.SystemService"},// elsewhere, in create() for example, call getPreferences passing
// the desired keys
create:function() {
this.inherited(arguments);
this.$.preferencesService.call({
keys: ["pref1", "pref2"]
},{
method: "getPreferences",
onSuccess: "gotPreferences",
onFailure: "gotPreferencesFailure"
});
}// setting the preferences uses a similar call. you'd execute this
// on button click, property change, or view change, for example
buttonClicked:function(source, event) {
this.$.preferencesService.call({
"pref1":"value of pref 1",
"pref2":"value of pref 2"
},{
method: "setPreferences",
onSuccess: "setPreferences",
onFailure: "setPreferencesFailure"
});
}
That works perfectly fine but is a little verbose for my taste. There's also an (undocumented) PreferencesService kind you can use. With that component, you're insulated from the underlying system service and instead call one of its two methods:
// passing an object of name/value pairs
updatePreferences(inPreferences)// passing an array of key names
fetchPreferences(inKeys, inSubscribe)
It also has an onFetchPreferences event to which you can listen to be notified when preferences have been loaded.
Finally, I've created a new kind as part of my enyo-extras repo called AutoPreferencesService. This component works by inspecting the published properties of its sub-kind and automatically loading those preferences and auto-wiring change events to update preferences. This allows you to create a app or feature-specific preferences interface that's more semantic while still insulating the app from directly interacting with the system service.
// create a kind inheriting from AutoPreferencesService
enyo.kind({
name:"myApp.ExamplePrefs",
kind:"extras.AutoPreferencesService",
published:{ // declare your preferences and default values
pref1:"",
pref2:""
}
});// add the new kind to you apps components block
{kind:"myApp.ExamplePrefs", onLoad:"prefsReady", name:"prefs"}// add onLoad callback handler
prefsReady:function() {
var pref1 = this.$.prefs.getPref1();
// do something useful with pref1
}// update preference as needed
saveButtonClicked:function() {
this.$.prefs.setPref1("new value");
}
This will be my new default way to deal with preferences. What do you think? Which approach is your preference or are you dealing with preferences a different way entirely?