Bug 1354682 Add transform to XPCOMUtils.defineLazyPreferenceGetter r=kmag

MozReview-Commit-ID: Lm59IHMNcy9

--HG--
extra : rebase_source : 796d9b0b7a6bf94782ebeeaf35d237176687c0ac
This commit is contained in:
Andrew Swan 2017-04-28 16:10:44 -07:00
Родитель 66aae8a48f
Коммит 46e486f880
2 изменённых файлов: 20 добавлений и 3 удалений

Просмотреть файл

@ -299,11 +299,16 @@ this.XPCOMUtils = {
* @param aOnUpdate
* A function to call upon update. Receives as arguments
* `(aPreference, previousValue, newValue)`
* @param aTransform
* An optional function to transform the value. If provided,
* this function receives the new preference value as an argument
* and its return value is used by the getter.
*/
defineLazyPreferenceGetter: function XPCU_defineLazyPreferenceGetter(
aObject, aName, aPreference,
aDefaultValue = null,
aOnUpdate = null)
aOnUpdate = null,
aTransform = val => val)
{
// Note: We need to keep a reference to this observer alive as long
// as aObject is alive. This means that all of our getters need to
@ -323,7 +328,7 @@ this.XPCOMUtils = {
// Fetch and cache value.
this.value = undefined;
let latest = lazyGetter();
aOnUpdate(data, previous, latest);
aOnUpdate.apply(aObject, data, previous, latest);
} else {
// Empty cache, next call to the getter will cause refetch.
@ -343,7 +348,7 @@ this.XPCOMUtils = {
function lazyGetter() {
if (observer.value === undefined) {
observer.value = Preferences.get(aPreference, aDefaultValue);
observer.value = aTransform(Preferences.get(aPreference, aDefaultValue));
}
return observer.value;
}

Просмотреть файл

@ -151,6 +151,18 @@ add_test(function test_defineLazyPreferenceGetter()
equal(obj.pref, "defaultValue", "Should return default value after pref is reset");
obj = {};
XPCOMUtils.defineLazyPreferenceGetter(obj, "pref", PREF, "a,b",
null, value => value.split(","));
deepEqual(obj.pref, ["a", "b"], "transform is applied to default value");
Preferences.set(PREF, "x,y,z");
deepEqual(obj.pref, ["x", "y", "z"], "transform is applied to updated value");
Preferences.reset(PREF);
deepEqual(obj.pref, ["a", "b"], "transform is applied to reset default");
run_next_test();
});