0

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

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

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

onBtnClick: function() {
  var someVar = this.value // This button element's value property
  this.someFunc(someVar);
}

someFunc: function(arg) {
  ...
}

When executing onclick, it gives an 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 the button element's value as well as this.someFunc in onBtnClick?

1 Answer 1

3

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
);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.