简体   繁体   中英

Unable to make user defined function call in Polymer

I'm implementing my website using Polymer 3.0 . I'm creating buttons in javascript . And I want to call user defined function on-click of the button.

I have tried adding event listener but the function is getting invoked as soon as the page is loaded. I have tried calling the function in bu.onclick function but the function is not getting invoked

//My code below

import { PolymerElement, html } from "./node_modules/@polymer/polymer/polymer-element.js";

class MyPage extends PolymerElement {
  static get template() {
    return html`
           <!-- Some useful div elements -->
           <iron-ajax 
                auto
                url= // my url
                handle-as="json"
                on-response="response"
                on-error="_statusFailed"
                last-error="{{lastError}}"
                last-response="{{lastResponse}}"
                debounce-duration="300">
        </iron-ajax>
     `;
}

constructor()
{
    super(); 
}

response()
{
    let list = this.shadowRoot.querySelector('#list');
    let bu = document.createElement('button');

    bu.onclick=function()
    {
        let a= this.value;
        console.log('Button Value: '+a);
        this.buttonprocessor(a);
    };
    list.append(bu);
}

buttonprocessor(msg)
{
    //some code 
}

When I click on the button created, I'm getting the following error

Uncaught TypeError: this.buttonprocessor is not a function
 at HTMLButtonElement.bu.onclick

Thanks beforehand.

I think the error message is pointing to the right direction this.buttonprocessor is not defined. Switch your function with a arrow function and it should be fine cause then this will point to the right class.

bu.onclick=() => {
    let a= this.value;
    console.log('Button Value: '+a);
    this.buttonprocessor(a);
};

this within a function state always points to the function itself you could also solve this like that:

var that = this;
bu.onclick=function()
{
    let a= this.value;
    console.log('Button Value: '+a);
    that.buttonprocessor(a);
};

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