Far too often I hear Cascades and C++ in the same sentence and not enough about Cascades and JavaScript. On that same token another common statement I hear about Cascades is QML is for UI and C++ is for logic. Though that is true, what is also true is QML can be used for UI and logic.

The way logic is handled in QML is through the use of JavaScript. At this point you may be asking yourself (or yelling at me through your screen) is I thought JavaScript was only for WebWorks applications!?!?

Well I am about to show you that is not true and give you three examples of how you can implement JavaScript into your Cascades project.

In-Line JavaScript

The easiest way to use JavaScript is to write it in-line with the rest of the QML. Let's demonstrate using a Label and a Button. So consider the following code in the onClicked signal, there is some JavaScript that defines a random number 1-3 and based off that number generates a phrase to have as the text of a Label

JavaScript Function Within the QML File

The next way you can have a JavaScript function defined within your QML file and call that function when necessary. So let's consider some similar code as above except we’ll define it as a function named phrase2() in the main Page {}.

Then we can have the onClicked signal of a Button call our "phrase2 ()" function

Function Defined in a Separate .js File

The third way is to define your JavaScript functions in a separate .js file then connect that file to your QML file. Again we'll create the same function, this time called phrase3(), within a file called otherFunctions.js

Next in your QML file declare the .js file

Now you can call that function inside of a Button onClicked signal by doing the following

For easy copy/pasting you can grab all the code here: https://github.com/bcs925/CrackBerry/tree/master/JavaScript_QML (It’s not a full project just add the main.qml and otherFunctions.js file to your project to see it in action)

There you have it, three ways to define/run JavaScript in QML. It is all a matter of preference/coding style of which way you choose to do it. Typically I like to use inline JavaScript for short/one time use functions.

I like to use defined functions within the QML for longer/used multiple times within that one QML file functions. And I like to use functions defined for very long or functions that will be used in multiple QML files.

Furthermore using JavaScript in your Cascades project will not negatively affect performance of your application. Now you know you can almost completely avoid using C++ in your Cascades apps, you have no reason not to give it a try!