Examples of use of getValueProvider

I was looking through the AuraDocs reference today and found a function on the Component javascript API that I had not seen before:

addValueProvider (String keyObject valueProvider)

Adds Custom ValueProviders to a component

Parameters

key : String string by which to identify the valueProvider. Used in
expressions in markup, etc.

valueProvider : Object
the object to request data from. Must implement .get(expression), can
implement .set(key,value).

I was able to find a few references to it’s use in the Aura github project here – line 80-86

var vp = {
        get: function(key, comp) {
            testUtils.assertStartsWith("SecureComponent", comp.toString(), "Component passed to value provider should be SecureComponent");
        }
    }
cmp.addValueProvider('foo', vp); 
cmp.get('foo.x');

But I was wondering if anyone had used this Component call and had a more concrete example of it’s use.

It looks like it could be handy in some situations (dynamic component creation the obvious case)

Answer

Custom Value Providers really doesn’t have any place in Lightning, as addValueProvider is used by the framework to provide $Label, c, v, etc. Dynamic component creation is facilitated by $A.createComponent, and you should use it for that purpose.

However, it could have a variety of useful utility purposes. For example, you could create a sessionStorage-backed storage provider:

controller.js

({
    init: function(component, event, helper) {
        component.addValueProvider(
            'storage',
            {
                get: function(key, comp) {
                    return sessionStorage.getItem(key);
                },
                set: function(key, value, comp) {
                    sessionStorage.setItem(key, value);
                }
            }
        );
    }
})

component

<aura:component >
    <aura:handler name="init" value="{!this}" action="{!c.init}" />
    <ui:inputText value="{!storage.value}" />
</aura:component>

This code will remember the value of ui:inputText, even when the user reloads the page, without wiring up aura:valueChange events or anything else. Go ahead and try it out.

The only apparent rule is that the data must already be available, because you have to return the correct value rather than fulfilling a Promise or using a callback.

The get and set methods are called explicitly through component.set and component.get, or you can call them implicitly by using expressions, just as you’d do with “c” or “v”.

Attribution
Source : Link , Question Author : Caspar Harmer , Answer Author : sfdcfox

Leave a Comment