简体   繁体   中英

Using JavaScript in Polymer element

I have an object of polymer:

<newfolder-element id="newfolderelement" popupStyle="width: 362px; height: 100px;">
    <span class="title">Utwórz nowy folder</span>
    <input type="text" class="ginput" style="width: 350px; padding: 5px;" placeholder="Nowy katalog" />
    <br />
    <button class="action blue"><span class="label">Utwórz</span></button>
    <button class="action red" id="cancelBtn"><span class="label">Anuluj</span></button>

        <script type="text/javascript">
            ...
        </script>

</newfolder-element>

I want to access dom elements in javascript, I tried this:

<script type="text/javascript">

                    Polymer('newfolderelement', {
                        domReady : function(){
                            $(this.shadowRoot.querySelector("#cancelBtn")).on('click', '#cancelBtn', function(){
                                console.log("clicked");
                            });
                        }
                    });
</script>

And this:

<script type="text/javascript>
                    $(this.shadowRoot.querySelector("#cancelBtn")).on('click', '#cancelBtn', function(){
                        console.log("clicked");
                    });

</script>

And this:

<script type="text/javascript>
                    $("#cancelBtn").click(function(){
                        console.log("clicked");
                    });

</script>

But all of above doesn't work. How to access dom elements inside polymer object ?

Why do you want to use jQuery, the Polymer already provides that functionality to you:

  • to access DOM elements use the $ map of the element, ie to get reference to the #cancelBtn use

    this.$.cancelBtn

  • to add an eventhandler use declarative event mapping , ie to add an click handler to the button

<button class="action red" id="cancelBtn" on-click="{{cancelClicked}}"></button>

and just add method cancelClicked to your component's script section.

  <script>
    Polymer('newfolder-element', {
      cancelClicked: function() {
         // do something
      }
    });
  </script>

This is much simpler and your component won't require additional library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM