Table of Contents

JavaScript

Block Group:Browser API
Block Icon:JavaScript block icon

Enables loading and running JavaScript and accessing JavaScript and HTML APIs.

This block is similar to the Script block, but it has two main differences:

The JavaScript is loaded in the global namespace of the page and must meet the following requirements:

If you make changes to the JavaScript code, these changes will take effect only if you refresh the browser—not simply if you close and reopen the .dg5 file.

In the example:

You can use getValue and setValue to interact with the custom parameters of the block. These custom parameters appear as properties that you can bind to other properties in DGLux5. The syntax to use setValue is setValue('a', newValue). This sets the value of the DGLux5 property a to newValue. The syntax to use getValue is getValue('a'). This returns the current value of the DGLux5 property a.


Input/Output Properties

These properties can take input and give output.

invoke causes the JavaScript to be loaded in the global source for the page and runs the init function.

autoRun specifies whether the script runs automatically.

scriptPath specifies the path to the JavaScript file. It can be a DGLux5 file path relative to the root, or it can be some other URL. The file extension must be .js.

initFunction specifies the name of the init function in the file.

The custom parameters set or return the values of properties that you can use in your script as needed.


Remarks


Model

This is a basic use of the block.

Dataflow Model Description
JavaScript dataflow model

The number displayed in the text component goes up by one each time the component is clicked. To achieve this effect:

  1. In your JavaScript file, set the value of the a property to the string "hello world n", with the value of n increasing by one each time the block is invoked.
  2. Bind the onClick event for the text component to invoke.
  3. Bind the value of a to the Text property of the text component.

Sample Code

The example on this page uses the following code:

function initTestJs(){
     var count = 0;
     function onInvoke(meta, getValue, setValue){
          setValue('a', 'hello world ' + count++);
     }
     return onInvoke;
}

Google Maps API Example

Use this code in the dataflow of a Google Map component to add a marker in Australia on the Google Map component. For initFunction, use initMapForDGLux.

function initMap(map) {
  var myLatLng = new google.maps.LatLng(-25.363, 131.044);

  var marker = new google.maps.Marker({
    position: myLatLng,
    map: map,
    title: 'Hello World!'
  });
}

function initMapForDGLux() {
     function runScript(meta, getValue, setValue) {
          if (meta.gmap != null) {
           initMap(meta.gmap);
          }
     }
     return runScript;
}

More Resources

These videos show the JavaScript block in use: