使用自定义元素从 AJAX XMLHttpRequest 外部访问方法

问题描述 投票:0回答:0

我有这个自定义 HTML 元素给我带来了麻烦。在 StaffList connectedCallback() 函数中,我必须调用父函数的外部函数,但是 addStaff() 的 super 关键字给了我一个错误。 “未捕获的语法错误:使用超级属性访问仅在方法内有效或方法内的评估代码”。我怎样才能访问请求之外的东西?


// A getter/setter for a disabled property.
get selected() {
  return this.hasAttribute('selected');
}
set selected(val) {
  // Reflect the value of the disabled property as an HTML attribute.
  if (val) {
    this.setAttribute('selected', '');
  } else {
    this.removeAttribute('selected');
  }
}

constructor() {
  // If you define a constructor, always call super() first!
  // This is specific to CE and required by the spec.
  super();
  /* handle clicks */
  for (const item of this.children) {
    item.addEventListener('click', e => {
      console.log(e);
    });
  }
}

connectedCallback() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      for (var item of JSON.parse(this.responseText)) {
        console.log(item);
        this.addStaff(item);
      }
    }
  };
  xhttp.open('GET', "/api/get_staff");
  xhttp.send();
}
}
customElements.define('staff-list', StaffList);```

I tried the keyword this but gives me the XML request object instead of my custom element.
javascript ajax super custom-element
© www.soinside.com 2019 - 2024. All rights reserved.