Passing variables with tap function


#1

How do I pass variables from view (xml) to “code behind”?

In angular I can do this

<Button text="Btn" tap="myTapFunc( varaibles )"></Button>

and in code behind I have this

export function myTapFunc(args:EventData) {
    console.log( variables? );
}

How do I do this in typescript?


#2

What do you need to pass that isn’t in the binding context?

Where you could just say

var dataItem = args.object.bindingContext;

But even then “args.object” is the JS object this works

<Button text="Btn" tap="myTapFunc" sup="bro"></Button>
var supValue = args.object.sup; //result = bro

#3

Ok thank you! Just playing around with vanilla {N} trying to understand the bindingContext and the connection between code behind and view model.

Probably not the right way to do it.

<Button text="About" path="about" tap="goTo"></Button>
<Button text="Products" path="products" tap="goTo"></Button>
imports...

let vm = new HomeViewModel();

export function navigatingTo(args:EventData) {
    let page = <Page>args.object;
    page.bindingContext = vm;
}

export function loaded(args:EventData) {
    vm.pageTitle = 'Hello World';
}
 
export function goTo(args) {
    console.log(args.object.path);
    // navigate to another page
}

#4

Yeah I think you have it, but also think of it this way… if you are binding to a model, in your tap you can also just GRAB the model values instead of passing things into the xml, then converting back in the js.

So lets say you had a repeater, and in each repeater element you had a Button wired to a tab event. The “bindingContext” in that button tab handler would be the data item that repeater item is bound to… SUUUUPER handy instead of trying to figureout an index and looking it up in the models array or something.

Food for thought!


#5

Thanks for the advice


#6

How I do this is,
say you have a button inside a list view template,
and you want to pass index when you click on button,

<Button text="Btn" anyPropertyName="{{ desiredVariable }}" tap="myTapFunc"></Button>

now in the tap handler use the args like this,

const button = args.object

console.log(button.anyPropertyName // you’ll get the desiredVariable’s value

so you can attach custom properties and access them in the tap handler


#7

@multishiv19 It’s a tad unnecessary to do that though right; you’d be treating it more like jQuery doing that. Like you’re taking your model object, exposing it to the xml object (in this case the button) to then re-consume it in the event.

When in the tap of the button you can just do

args.object.bindingContext 

to literally get the exact object it was bound to

var dataItem = args.object.bindingContext;
console.log(dataItem.anyProperyName);

#8

@sitefinitysteve
Agreed. :+1: