+1 vote
1.1k views
in Coach Views by (30.6k points)

1 Answer

0 votes
by (30.6k points)

In a coach view's JavaScript, this is the coach view object only while the framework calls your handler (load, view, change, unload, or a control event). As soon as you go into a nested function - a callback of an Ajax service, a setTimeout, a DOM event listener, an array method - this is rebound by JavaScript's rules to whatever called that function (window, the DOM element, undefined in strict mode). var _this = this; captures the view in a normal variable that closures can see:

// load handler of a coach view
var _this = this;                                   // capture the view
this.context.element.querySelector("button").addEventListener("click", function () {
  // here "this" is the <button>, not the view
  _this.context.binding.set("value", "clicked");    // correct
  _this.ui.get("Status").setText("saved");          // works; this.ui would be undefined
});
setTimeout(function () { _this.refresh(); }, 1000); // same reason

Modern alternatives that do the same: arrow functions keep the lexical this (btn.addEventListener("click", () => this.context...) - fine in BAW 20+ coaches, not in old browsers), or fn.bind(this). The UI Toolkit avoids the problem in control events by passing me (the control) as an argument - use me there instead of this (question 2659).

Rule: at the top of every coach view handler that uses callbacks write var _this = this; and never use bare this inside a nested function.

References

Related questions

+1 vote
1 answer 2.7k views
0 votes
1 answer 1.1k views
0 votes
1 answer 1.4k views
+1 vote
1 answer 1.2k views
0 votes
1 answer 3.1k views
0 votes
1 answer 1.6k views
0 votes
1 answer 1.9k views
0 votes
1 answer 4.0k views
0 votes
1 answer 1.1k views
0 votes
1 answer 1.7k views
0 votes
1 answer 1.2k views
0 votes
1 answer 1.0k views
0 votes
1 answer 3.7k views
0 votes
1 answer 1.7k views

723 questions

807 answers

98 comments

4.9k users

Join BPM Community Discord Channel

Welcome to BPM Tips Q&A, Community wiki/forum where you can ask questions and receive answers from other IBM BPM experts and members of the community. Users with 2000 points will automatically be promoted to expert level.
Created by Dosvak LLC
Our Youtube Channel
...