Try placing the script in the enter and exit events. I used the enter event to show the border always so that when users enter the field they can see the boundaries. For this, I just used:
this.resolveNode("$").border.presence = "visible";
Then in the exit event I placed the following codes to evaluate whether the field was null and show or hide the border (the exit event works for this because the code only affects the object when it is changed and exited). Setting the height to null reduces the field size so you don't have a borderless text field taking up space with the empty/unfilled area of the object (basically it sizes the object to shrink to fit the text):
if (this.resolveNode("$").rawValue != null && this.resolveNode("$").rawValue != "") {
this.resolveNode("$").border.presence = "hidden";
this.resolveNode("$").h = "";
}
if (this.resolveNode("$").rawValue == null || this.resolveNode("$").rawValue == "") {
this.resolveNode("$").border.presence = "visible";
}