2020-03-15

Polymer 3 dom-bind event handling

Original intent

is to update the text when component.selection is changed
index-0.html
<textarea style="width: 100%;height: 9em" id="configtext"></textarea>
<button onclick=" navigator.clipboard.writeText(configtext.value) ">&boxbox; Copy</button>

<webcomponents-element visible="true" id="webcomponentsElement" ></webcomponents-element>
<script>
    window.addEventListener("load",()=>{
        webcomponentsElement.addEventListener("selection-changed",(ev)=>{
            configtext.value=webcomponentsElement.selection.replace( /,/g , ",\n");
        });
    });
</script>

using dom-bind

The change handler is still initialized in SCRIPT code:
index-1.html
<dom-bind id="configurator">
    <template>

        <textarea style="width: 100%;height: 9em" id="configtext"></textarea>
        <button onclick=" navigator.clipboard.writeText(configtext.value) ">&boxbox; Copy</button>

        <webcomponents-element visible="true" id="webcomponentsElement"
                               on-selection-changed="onSelectionChanged"
        ></webcomponents-element>
    </template>
</dom-bind>
<script>
    configurator.onSelectionChanged = function (e) {
        configtext.value = webcomponentsElement.selection.replace(/,/g, ",\n");
    };
</script>

Final version - The power of declarative programming!

No JavaScript, binding only via sel variable scoped in binding context of dom-bind.
index.html
<dom-bind>
    <template>
        <textarea style="width: 100%;height: 9em" id="configtext" value="{{sel::change}}"></textarea>
        <button onclick=" navigator.clipboard.writeText(configtext.value) ">&boxbox; Copy</button>

        <webcomponents-element visible="true" id="webcomponentsElement" selection="{{sel}}"></webcomponents-element>
    </template>
</dom-bind>

1 comment:

  1. working code is in project https://github.com/EPA-WG/web-elements-loader

    ReplyDelete