Using App Connect with JavaScript Functions
We will show you a couple of simple examples, which show you how to do this but it applies for any complex function you might be using.
Using App Connect Expressions in JavaScript Functions
You can use dmx.parse
to parse expressions inside JavaScript. We have the following JavaScript function:
<script>
function myFunction() {
var myVar = 'abc';
console.log(myVar);
}
</script>
But we want to use an App Connect expression for the variable myVar
, let’s say an App Connect variable value, which changes dynamically:
<dmx-value id="var1"></dmx-value>
All we need to do is to add dmx.parse('dynamic_expression')
as a value for our JavaScript variable:
<script>
function myFunction() {
var myVar = dmx.parse('var1.value');
console.log(myVar);
}
</script>
NOTE: This can be any dynamic expression, not only an App Connect variable.
So the results can be seen when we run the function:
Accessing JavaScript Variables Values with App Connect
You can use dmx.app.set('varName', varName)
to access JavaScript Variables Values with App Connect. We have the following JavaScript function, which contains an object:
<script>
function myFunction() {
var car = {type:"Fiat", model:"500", color:"white"};
}
</script>
NOTE: it can be a simple variable as well.
We want to use the object values within App Connect. In our example, we will use the values with an Inner Text dynamic attribute on the page:
<p dmx-text=""></p>
In order to make the object properties/values available for App Connect, we add dmx.app.set
to the function:
<script>
function myFunction() {
var car = {type:"Fiat", model:"500", color:"white"};
dmx.app.set('car', car);
}
</script>
The first value (in single quotes) is how you want to name the object (or variable) in App Connect, the second value is the object (or variable) name from your JavaScript function. It’s a good practice to keep them the same.
Then on our page we add:
<p dmx-text="car.color"></p>
And when we run the function, the car color will be displayed on the page:
These are the basics of using JavaScript with App Connect, you can extend them according to your needs.