Discuss

Using App Connect with JavaScript Functions

In some cases it's required to read a JavaScript variable or object values and use them in App Connect. In other cases it's required to use a dynamic App Connect expression in your own custom JavaScript functions. Although we don't provide a visual interface for these operations, both are possible with App Connect.

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:

Screenshot_5

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:

Screenshot_6


These are the basics of using JavaScript with App Connect, you can extend them according to your needs.