NativeScript button event not firing

I spent a bit of time trying to understand why a tap event failed to fire on a button in NativeScript. Here was the original code segments:

Button Code

view plain print about
1<Button text="Pay Debt" tap="payDebtAction" visibility="{{ debt===0 ? 'collapse', 'visible'}}" />

Tap Event Handler Function

view plain print about
1exports.payDebtAction = function(args){
2 var page = args.object;
3 console.log("paydebt");
4}

The intent of this code was to hide the Pay Debt button if there was no debt. In exports.payDebtAction(), there was a call to the view-model to reduce the debt by the appropriate amount. When I ran the code, I did not get any output in the console. Thus, the code to reduce the debt never ran and the button never disappeared from the view.

Using the Throw-Stuff-At-The-Wall method, I eventually removed the visibility attribute from the Button declaration, and handled hiding the button in the code behind file like this:

view plain print about
1<Button text="Pay Debt" tap="payDebtAction" id="payDebtButton" />

Tap Event Handler Function

view plain print about
1exports.payDebtAction = function(args){
2 var page = args.object;
3 console.log("paydebt");
4 GameViewModel.payDebt();
5 var debt = GameViewModel.get("debt");
6 if( debt < 1){
7 View.getViewById(page, "payDebtButton").visibility='collapse';
8 }
9};

Notice the id attribute on the button. I use that ID to get a reference to the control, then set the visibility property in javascript, not in the view XML. This code works as expected.

I'm not 100% sure what I learned, but perhaps if there is a way to sum it up, is to not try to do so much in the XML layer. The JS layer is a lot more powerful anyways.

There are no comments for this entry.

Add Comment Subscribe to Comments