How to create "tap=" equivalent in javascript?



I have an existing pure {N} page (i.e., no TypeScript, no Angular, no Vue) that I now need to build from javascript so as to allow for a variable number of tabs. I’ve found very little documentation on this, really just some sample code in The Nativescript Book. I’ve been able to piece most of this together, but am getting stuck on defining simple tap events. For example, if I have this line of XML:

<Label class="route-more" col="2" row="0" tap="onMoreTap" text="{{ showInfo ? ' &xf056; ' : ' &#xf055; ' }}"/>

I can create this from the .js file thusly:

    let expander = new Label();
    expander.col = '2';
    expander.row = '0';
    expander.className = 'route-more';
    expander.tapEvent = 'onMoreTap';
      targetProperty: "text", sourceProperty: 'showInfo',
      expression: "showInfo ? ' \uf056 ' : ' \uf055 '"

But, the tapEvent code, above, doesn’t work, and I think I need to define my own event listener. The Event doc kinda describes this, but I don’t see how that code could work, as it appears incomplete:

const Button = require("tns-core-modules/ui/button").Button;
const testButton = new Button();
testButton.text = "Test";

let onTap = function(args: EventData) {
  console.log("Hello World!");
//Adding a listener with the short syntax
testButton.on(buttonModule.Button.tapEvent, onTap, this);

//Adding a listener with the full syntax
testButton.addEventListener(buttonModule.Button.tapEvent, onTap, this);

(Notice that buttonModule is undefined.)

So, the question: how do I create in javascript the equivalent of the tap=‘onMoreTap’ xml property?


What you have copied from event doc is the right way of doing it in JS - adding tap listener. You may simply name it "tap" or Button.tapEvent


@manojdcoder - thanks, as always, for your response!

I still don’t know what to make of buttonModule in the doc, though. I have three objects to add tap handlers to: an image, a button, and a label. I started with the image, and tried,

const Image = require("tns-core-modules/ui/image").Image;
let routeArrow = new Image;

then I tried:

routeArrow.on(Image.Image.tapEvent, exports.onRouteTap, this);

Rationale: I’ve seen lots of sample code that defines Module variables such as

const ImageModule = require("tns-core-modules/ui/image").Image;

But, my code above fails with Image.Image being undefined (really, as I expected).

So, I tried,

routeArrow.on(Image.tapEvent, exports.onRouteTap, this);

And while this doesn’t throw an exception, the onRouteTap function never receives control, either.

Any pointers on the syntax here? I’m still poking at it but haven’t made any progress.


OK, was able to play with this and get it to work. Here’s a working syntax:

routeArrow.addEventListener("tap", exports.onRouteTap, this);