Using JavaScript events handlers in UWA widgets
Deep in the confines of the - very complete - UWA documentation, lies informations that might be important enough to be push to the surface on this blog.
The page we are talking about is the aptly-named “Using events in UWA“. Let’s sum this already short page up: simply put, inline events handlers cannot work properly in UWA, so you are asked to assign them dynamically.
By inline event handlers, we understand attributes such as onclick or onmouseover, which are placed directly within the HTML code, like so:
<htmlelement onmouseover="doSomething();" />
Inline event handlers’ issues are well documented, one of the most flagrant ones being that they imply mixing up structure (HTML) with behavior (JavaScript), which is a big no-no if you want to code cleanly.
Furthermore, within the UWA framework, using an inline event handler would require that handler to be set globally, rather than on the target widget itself.
The solution exists, of course: using the “traditional event registration model“. That means, instead of using onclick as an attribute of the HTML element, you declare it using JavaScript. Hence, you would turn this piece of code:
<textarea onfocus="pieceOfCode(this);" >
Default text
</textarea>
…into this one (where the textarea tag has not onfocus attribute)…
widget.onLoad = function() {
var textarea = widget.body.getElementsByTagName("textarea")[0];
textarea.onfocus = pieceOfCode;
}
This way, structure and behavior stay separated, and you can even assign event handlers on the fly while created HTML tags with the DOM. But, as put highlighted by a recent thread on the forum, don’t forget to make sure that the tags you are targeting have indeed already been created.
The DOM is great and powerful, but as they say in the movies, with great powers come great responsibilities - so assign your event handlers responsibly ![]()
Tags: dom, javascript, uwa