WAB - "this" Keyword Conflict with Button Element

434
3
Jump to solution
03-23-2023 04:08 PM
XuanKuai
New Contributor III

I created a button element with an onclick using the following method:

domConstruct.create('button', {
  ...
  value: someValue;
  onclick: this.onBtnClick
}, someNode);

The onBtnClick method uses the value of the button element, and also calls another function:

onBtnClick: function() {
  var someVar = this.value;
  this.someFunc();
},

someFunc: function() {
  ...
},

When executing the onclick, it gives this error:

Uncaught TypeError: this.someFunc is not a function at HTMLButtonElement.onBtnClick

However, the button element's value could be correctly fetched by this.value. So it looks like in the onBtnClick method the this keyword only refers to the button element instead of the entire widget. Is there anyway to use both this.value and this.someFunc in onBtnClick?

0 Kudos
1 Solution

Accepted Solutions
KenBuja
MVP Esteemed Contributor

You have to use the hitch function in the dojo/_base/lang module when using "this" in callback functions. Here is how I use in my code to run the function "applyEdits" when clicking on a button

import lang from "dojo/_base/lang";

domConstruct.create(
  "div",
  {
    class: "jimu-btn " + settingName,
    style: "margin-top: 5px; margin-bottom: 5px;",
    onclick: lang.hitch(this, function (evt) {
      this.applyEdits(evt);
    })
  },
  container
);

View solution in original post

0 Kudos
3 Replies
KenBuja
MVP Esteemed Contributor

You have to use the hitch function in the dojo/_base/lang module when using "this" in callback functions. Here is how I use in my code to run the function "applyEdits" when clicking on a button

import lang from "dojo/_base/lang";

domConstruct.create(
  "div",
  {
    class: "jimu-btn " + settingName,
    style: "margin-top: 5px; margin-bottom: 5px;",
    onclick: lang.hitch(this, function (evt) {
      this.applyEdits(evt);
    })
  },
  container
);
0 Kudos
XuanKuai
New Contributor III

Thank you! This enables me to use the function while also using evt.target.value to access the button's value. And thank you for answering the same question on the other website!

0 Kudos
KenBuja
MVP Esteemed Contributor

Glad to help you out!

0 Kudos