Skip to content

Component CPart - setValue helper method #25

Open

Description

@michaelpb

As a component developer, I often want to write components that behave externally like inputs.


Possible solution:

setValue(payload) {
   this.element.value = payload
   this.element.dispatchEvent(new window.Event('change'));
}

This allows for code like:

<button @click:=component.setValue payload="green">Set to green</button>
<button @click:=component.setValue payload="blue">Set to blue</button>

Also for completeness, if this is ever invoked, add a stateChangedCallback to component, and some way it writes it to a state (maybe a special state variable ALWAYS called "value")

setValue(payload) {
   if (!this.element.stateChangedCallback) {
      this.element.stateChangedCallback = (name, newValue) => {
           this.element.cparts.state.value = newValue;
           this.element.value = payload
           element.rerender();
      };
   }
   this.element.stateChangedCallback('', payload);
   this.element.dispatchEvent(new window.Event('change'));
}

This could be also be included as a "recipe", like a documented patch.

Activity

  1. michaelpb commented on Feb 22, 2023

    @michaelpb
    ContributorAuthor

    Recipe is below:

    // Include this and use setValue to make a component behave a bit like an input
    // with a change event
    
    let isBool = null;
    
    function initializedCallback() {
        element.stateChangedCallback = (function (name, newValue, el) {
            this.value = newValue;
            if (isBool) {
                this.value = !!this.value;
            }
            this.cparts.state.value = this.value; // ensure set
            this.rerender();
        }).bind(element);
        if (isBool === null) {
            isBool = typeof state.value === 'boolean';
        }
        state.value = props.value || '';
        if (isBool) {
            state.value = !!state.value;
        }
        element.value = state.value;
    }
    
    function setValue(payload) {
        if (isBool) {
            element.value = !element.value;
        } else {
            element.value = payload;
        }
        state.value = element.value;
        element.dispatchEvent(new window.Event('change'));
    }

    Already in repo, just needs docs (when Recipe system is final)

    <Script -src="https://unpkg.com/mdu.js@0.0.31/mdu/libraries/widgetslib/formHelper.js"></Script>
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    recipeWhat should be a future recipe

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions