gitaarik / lit-state

Simple shared component state management for LitElement.
https://gitaarik.github.io/lit-state/build/
GNU Lesser General Public License v3.0
139 stars 11 forks source link

example of options from a method - without decorator #4

Closed christophe-g closed 3 years ago

christophe-g commented 3 years ago

Hey - thanks a lot for this new release. I have been playing with it today, and looks like a great opportunity to drop Redux boilerplate from my app.

I am having some difficulties to make the following use case (from the docs, below) work.

The goal is to have a customizable way to do smth when a state var updates (example: update document lang and dir attribute when language var updates). From what I get from the docs, it seems providing options from a method is supposed to tackle such cases.

Also, what would be the advantages (other than proper scoping the callback) over smth like (with a handled calling the callback function on update) :

const stateVars = {
    language: {
        handler: MyFirebaseHandler,
        callback: (value) => ... do stuff ,
        key: 'language',
        initialValue: 'fr'
    }
};

class AppState extends LitFirebaseState ... extends LitState  {

    static get stateVars() {
        return stateVars;
    }
}

Providing options from a method To give you access to the this objects on your state instance, you can additionally add options to your handler through a method.

class DemoState extends LitState {

   @stateVar({ handler: MyCustomHandler })
    myVar() {
       // This object returned, will be added to the `options` that are
       // given to the constructor of the `handler` class.
       return {
           callback: () => this.callback();
       };
   }

}
christophe-g commented 3 years ago

Closing as appState.addObserver((name) => if(name === 'language') {doSthm}) covers this use case much better !

gitaarik commented 3 years ago

yes, and you can actually also observe a specific stateVar, so you don't have to do the if (name === 'language'):

appState.addObserver(myObserver, ['language']);

And yes, you can also create a custom stateVar Handler that does something specific when a state changes. However, you don't need the method decorating feature for that. You just need to override the get and/or set of the stateVar handler.

You only need to decorate a method when you need access to the this reference or your state class. For callbacks for example.

christophe-g commented 3 years ago

appState.addObserver(myObserver, ['language']);

Ah, great, thank you ! and thanks for this lib, really. C.