KeithLu
KeithLu

Reputation: 91

Is there a common way to get a polymer element's dataset or attributes?

I used "paper-input" and "paper-button" in my own polymer element, since the e.target is not the element which bind the dataset and attributes, the way to get dataset in event handler is different. Is there a common way to get a polymer element's dataset or attributes?

<dom-module id="login-form">
<template>
    <div>
        <form action="/login" method="POST">
            <paper-input id="username" >
                <paper-icon-button on-click="clearInput" data-elmid="username" suffix >
                </paper-icon-button>
            </paper-input>

            <paper-button class="custom indigo" data-hello="world" on-click="loginValidate">
                Login
            </paper-button>
        </form>

    </div>
</template>

<script>
    (function() {
        Polymer({
            is: 'login-form',
            clearInput: function(e) {
                console.log(e.target.dataHost.dataset.elmid);
            },
            loginValidate: function(e) {
                console.log(e.target.dataset.hello);
            }
        });
    })();
</script>
</dom-module>

Upvotes: 1

Views: 1343

Answers (1)

user600838
user600838

Reputation:

It looks like your binding is slightly incorrect.

To bind a data- attribute and be able to access it with the dataset property, use $= in data-foo$=value [*]. Otherwise, Polymer converts the attribute into a camelCase property on the element (i.e., data-foo= would be accessed by element.dataFoo, whereas data-foo$= would be element.dataset.foo). In your example, Polymer created a dataElmid property on <paper-input>, and dataHello on <paper-button>.

Here's the corrected example:

<paper-input id="username">
    <!-- change `data-elmid="username"` to  `data-elmid$="username"` -->
    <paper-icon-button on-click="clearInput" data-elmid$="username" suffix >
    </paper-icon-button>
</paper-input>

<!-- change `data-hello="world"` to  `data-hello$="world"` -->
<paper-button class="custom indigo" data-hello$="world" on-click="loginValidate">
    Login
</paper-button>

Upvotes: 4

Related Questions