简体   繁体   English

无法在 Polymer 中进行用户定义的函数调用

[英]Unable to make user defined function call in Polymer

I'm implementing my website using Polymer 3.0 .我正在使用Polymer 3.0实现我的网站。 I'm creating buttons in javascript .我正在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我尝试在 bu.onclick 函数中调用该函数,但该函数没有被调用

//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.我认为错误消息指向正确的方向 this.buttonprocessor 未定义。 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:函数状态中的 this 始终指向函数本身,您也可以这样解决:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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