At first, you got a nicely structured Alloy controller, but as you go on, new features keep getting added, and slowly but surely you end up with a monster. Your XML file might still look okay, but your controller file starts getting hundreds of lines and the end is not in sight. Sound familiar?

How do you restructure such a mess into a well-structured file again without rewriting the entire thing? It is easier than you might think.

There are actually a few steps you can take to make refactoring easy, like moving more UI elements to XML. From there, it is easy to structure your code. Just follow along with a simple one in your code, and then apply that to all of them, one by one, until your code is clean again.

Move eventListeners to XML

The first easy fix is to move any eventListeners on existing UI elements to your XML file. This saves you quite some space in your controller and gives you a clear overview of which UI components listen for user input. If you have this now

JavaScript

1

$.myButton.addEventListener('click', myFunction);

You should replace it with this:

HTML

1

<Button id="myButton" onClick="myFunction" />

Any event is always preceded with on and then your event starts with an uppercase character. The rest of the casing on the event should remain the same.

If you have an anonymous function like this

JavaScript

1

$.myButton.addEventListener('click', function(e) {});

Then you should first name your function, I usually give the functions a predictable name which is structured like handle[id][eventName], like this: handleMyButtonClick(), and then you can again move the eventListeners to your XML file.

If you have a UI element that sets a different listener based on a certain condition, then you need a new function that handles all these conditions. For example, if you have a Button that either checks or unchecks something, create a function, and perform the needed logic in that function to determine if you need to do a check or uncheck. By creating multiple event listeners for the same UI element you’re creating more complications in your code which makes things much harder to debug.

There is absolutely no need for two listeners. And in the case you have certain listeners that do nothing in certain situations, like a button click on a greyed-out button, then again, do this verification inside the handler function, do not add or remove listeners on the fly.

You can even store state in the button element itself, as custom properties on any UI element are allowed. So you could set $.myButton.hasDisabledState = true and read this property inside your click handler. These custom properties can also be set in the XML and

#tutorial #web dev #controller #refactor #alloy controller #javascipt

How to Refactor Big Alloy Controllers
1.20 GEEK