简体   繁体   中英

Bind Polymer 2.x event handler to a global function?

I have some Polymer elements that are not inside an element/app, and I can't figure out how to attach their event handlers, such as on-click , to a global javascript function.

For example, let's say my code looks something like this

<head>
    // Import stuff...

    function login(){
        // Do stuff
    }
</head>
<body unresolved>    
    <dom-if id="signInItem">
        <template>
            <paper-button on-tap="login"><iron-icon icon="icons:account-circle"></iron-icon> &nbsp; Log in</paper-button>
        </template>
    </dom-if>
</body>

This won't work, because on-tap expects to bind to a property of an enclosing element (I guess). What are my options?

give some id for paper-button

<paper-button id="button"></paper-button>

in javascript you can add eventlistener as shown below

    this.$.button.addEventListener('click', e => {
    console.log("clicked");
     // write your code 
    });

or you can write your code in seperate function

ready() {
  super.ready();
  this.$.button.addEventListener('click', e => this.handleClick(e));
}
handleClick(e) {
   console.log(e);
}

If you like to fire a function not in polymer you may call;

this.dispatchEvent(new CustomEvent('login', { bubbles: true, composed: true, detail: true }));

This will fire your login listen in global js (ie. main.js) as below;

addEventListener('login', function (e) {
      // Do something for login 

})

EDIT: I think you also need to change dom-if to dom-bind in order to bind this code as its at root level

You can always forward a call to a local class member function (MyElement.login) to a global namespace:

/* 1 */ class MyElement extends Polymer.Element {
/* 2 */     // ...
/* 3 */     
/* 4 */     login: (() => (evt) (MyGlobalNamespace || window).login.bind(this))()
/* 5 */ }

You can even omit the surrounding closure function - if you're not using this within the implementation of login -, simplifying line 4 to: login: (MyGlobalNamespace || window).login

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