1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
|
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en_US" lang="en_US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- javascriptblocks.qdoc -->
<title>Qt 4.8: Integrating JavaScript</title>
<link rel="stylesheet" type="text/css" href="style/offline.css" />
</head>
<body>
<div class="header" id="qtdocheader">
<div class="content">
<a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a>
</div>
<div class="breadcrumb toolblock">
<ul>
<li class="first"><a href="index.html">Home</a></li>
<!-- Breadcrumbs go here -->
<li>Integrating JavaScript</li>
</ul>
</div>
</div>
<div class="content mainContent">
<div class="toc">
<h3><a name="toc">Contents</a></h3>
<ul>
<li class="level1"><a href="#inline-javascript">Inline JavaScript</a></li>
<li class="level1"><a href="#separate-javascript-files">Separate JavaScript files</a></li>
<li class="level2"><a href="#code-behind-implementation-files">Code-Behind Implementation Files</a></li>
<li class="level2"><a href="#stateless-javascript-libraries">Stateless JavaScript libraries</a></li>
<li class="level2"><a href="#importing-one-javascript-file-from-another">Importing One JavaScript File From Another</a></li>
<li class="level1"><a href="#running-javascript-at-startup">Running JavaScript at Startup</a></li>
<li class="level1"><a href="#javascript-and-property-binding">JavaScript and Property Binding</a></li>
<li class="level1"><a href="#receiving-qml-signals-in-javascript">Receiving QML Signals in JavaScript</a></li>
<li class="level1"><a href="#qml-javascript-restrictions">QML JavaScript Restrictions</a></li>
</ul>
</div>
<h1 class="title">Integrating JavaScript</h1>
<span class="subtitle"></span>
<!-- $$$qdeclarativejavascript.html-description -->
<div class="descr"> <a name="details"></a>
<p>QML encourages building UIs declaratively, using <a href="propertybinding.html">Property Binding</a> and the composition of existing <a href="qdeclarativeelements.html">QML Elements</a>. To allow the implementation of more advanced behavior, QML integrates tightly with imperative JavaScript code.</p>
<p>The JavaScript environment provided by QML is stricter than that in a web browser. In QML you cannot add, or modify, members of the JavaScript global object. It is possible to do this accidentally by using a variable without declaring it. In QML this will throw an exception, so all local variables should be explicitly declared.</p>
<p>In addition to the standard JavaScript properties, the <a href="qdeclarativeglobalobject.html">QML Global Object</a> includes a number of helper methods that simplify building UIs and interacting with the QML environment.</p>
<a name="inline-javascript"></a>
<h2>Inline JavaScript</h2>
<p>Small JavaScript functions can be written inline with other QML declarations. These inline functions are added as methods to the QML element that contains them.</p>
<pre class="cpp"> Item {
function factorial(a) {
a <span class="operator">=</span> parseInt(a);
<span class="keyword">if</span> (a <span class="operator"><</span><span class="operator">=</span> <span class="number">0</span>)
<span class="keyword">return</span> <span class="number">1</span>;
<span class="keyword">else</span>
<span class="keyword">return</span> a <span class="operator">*</span> factorial(a <span class="operator">-</span> <span class="number">1</span>);
}
MouseArea {
anchors<span class="operator">.</span>fill: parent
onClicked: console<span class="operator">.</span>log(factorial(<span class="number">10</span>))
}
}</pre>
<p>As methods, inline functions on the root element in a QML component can be invoked by callers outside the component. If this is not desired, the method can be added to a non-root element or, preferably, written in an external JavaScript file.</p>
<a name="separate-javascript-files"></a>
<h2>Separate JavaScript files</h2>
<p>Large blocks of JavaScript should be written in separate files. These files can be imported into QML files using an <tt>import</tt> statement, in the same way that <a href="qdeclarativemodules.html">modules</a> are imported.</p>
<p>For example, the <tt>factorial()</tt> method in the above example for <a href="#inline-javascript">Inline JavaScript</a> could be moved into an external file named <tt>factorial.js</tt>, and accessed like this:</p>
<pre class="cpp"> import <span class="string">"factorial.js"</span> as MathFunctions
Item {
MouseArea {
anchors<span class="operator">.</span>fill: parent
onClicked: console<span class="operator">.</span>log(MathFunctions<span class="operator">.</span>factorial(<span class="number">10</span>))
}
}</pre>
<p>Both relative and absolute JavaScript URLs can be imported. In the case of a relative URL, the location is resolved relative to the location of the <a href="qdeclarativedocuments.html">QML Document</a> that contains the import. If the script file is not accessible, an error will occur. If the JavaScript needs to be fetched from a network resource, the component's <a href="qdeclarativecomponent.html#status-prop">status</a> is set to "Loading" until the script has been downloaded.</p>
<p>Imported JavaScript files are always qualified using the "as" keyword. The qualifier for JavaScript files must be unique, so there is always a one-to-one mapping between qualifiers and JavaScript files. (This also means qualifiers cannot be named the same as built-in JavaScript objects such as <tt>Date</tt> and <tt>Math</tt>).</p>
<a name="code-behind-implementation-files"></a>
<h3>Code-Behind Implementation Files</h3>
<p>Most JavaScript files imported into a QML file are stateful, logic implementations for the QML file importing them. In these cases, for QML component instances to behave correctly each instance requires a separate copy of the JavaScript objects and state.</p>
<p>The default behavior when importing JavaScript files is to provide a unique, isolated copy for each QML component instance. The code runs in the same scope as the QML component instance and consequently can can access and manipulate the objects and properties declared.</p>
<a name="stateless-javascript-libraries"></a>
<h3>Stateless JavaScript libraries</h3>
<p>Some JavaScript files act more like libraries - they provide a set of stateless helper functions that take input and compute output, but never manipulate QML component instances directly.</p>
<p>As it would be wasteful for each QML component instance to have a unique copy of these libraries, the JavaScript programmer can indicate a particular file is a stateless library through the use of a pragma, as shown in the following example.</p>
<pre class="cpp"> <span class="comment">// factorial.js</span>
<span class="operator">.</span>pragma library
function factorial(a) {
a <span class="operator">=</span> parseInt(a);
<span class="keyword">if</span> (a <span class="operator"><</span><span class="operator">=</span> <span class="number">0</span>)
<span class="keyword">return</span> <span class="number">1</span>;
<span class="keyword">else</span>
<span class="keyword">return</span> a <span class="operator">*</span> factorial(a <span class="operator">-</span> <span class="number">1</span>);
}</pre>
<p>The pragma declaration must appear before any JavaScript code excluding comments.</p>
<p>As they are shared, stateless library files cannot access QML component instance objects or properties directly, although QML values can be passed as function parameters.</p>
<a name="importing-one-javascript-file-from-another"></a>
<h3>Importing One JavaScript File From Another</h3>
<p>If a JavaScript file needs to use functions defined inside another JavaScript file, the other file can be imported using the <a href="qml-qt.html#include-method">Qt.include()</a> function. This imports all functions from the other file into the current file's namespace.</p>
<p>For example, the QML code below left calls <tt>showCalculations()</tt> in <tt>script.js</tt>, which in turn can call <tt>factorial()</tt> in <tt>factorial.js</tt>, as it has included <tt>factorial.js</tt> using <a href="qml-qt.html#include-method">Qt.include()</a>.</p>
<table class="generic">
<tr valign="top" class="odd"><td rowspan="2"><pre class="qml"> import QtQuick 1.0
import "script.js" as MyScript
<span class="type"><a href="qml-item.html">Item</a></span> {
<span class="name">width</span>: <span class="number">100</span>; <span class="name">height</span>: <span class="number">100</span>
<span class="type"><a href="qml-mousearea.html">MouseArea</a></span> {
<span class="name">anchors</span>.fill: <span class="name">parent</span>
<span class="name">onClicked</span>: {
<span class="name">MyScript</span>.<span class="name">showCalculations</span>(<span class="number">10</span>)
<span class="name">console</span>.<span class="name">log</span>(<span class="string">"Call factorial() from QML:"</span>,
<span class="name">MyScript</span>.<span class="name">factorial</span>(<span class="number">10</span>))
}
}
}</pre>
</td><td ><pre class="js"> <span class="comment">// script.js</span>
<span class="name">Qt</span>.<span class="name">include</span>(<span class="string">"factorial.js"</span>)
<span class="keyword">function</span> <span class="name">showCalculations</span>(<span class="name">value</span>) {
<span class="name">console</span>.<span class="name">log</span>(<span class="string">"Call factorial() from script.js:"</span>,
<span class="name">factorial</span>(<span class="name">value</span>));
}</pre>
</td></tr>
<tr valign="top" class="even"><td ><pre class="js"> <span class="comment">// factorial.js</span>
<span class="keyword">function</span> <span class="name">factorial</span>(<span class="name">a</span>) {
<span class="name">a</span> <span class="operator">=</span> <span class="name">parseInt</span>(<span class="name">a</span>);
<span class="keyword">if</span> (<span class="name">a</span> <span class="operator"><=</span> <span class="number">0</span>)
<span class="keyword">return</span> <span class="number">1</span>;
else
<span class="keyword">return</span> <span class="name">a</span> <span class="operator">*</span> <span class="name">factorial</span>(<span class="name">a</span> <span class="operator">-</span> <span class="number">1</span>);
}</pre>
</td></tr>
</table>
<p>Notice that calling <a href="qml-qt.html#include-method">Qt.include()</a> imports all functions from <tt>factorial.js</tt> into the <tt>MyScript</tt> namespace, which means the QML component can also access <tt>factorial()</tt> directly as <tt>MyScript.factorial()</tt>.</p>
<a name="running-javascript-at-startup"></a>
<h2>Running JavaScript at Startup</h2>
<p>It is occasionally necessary to run some imperative code at application (or component instance) startup. While it is tempting to just include the startup script as <i>global code</i> in an external script file, this can have severe limitations as the QML environment may not have been fully established. For example, some objects might not have been created or some <a href="propertybinding.html">Property Binding</a>s may not have been run. <a href="#qml-javascript-restrictions">QML JavaScript Restrictions</a> covers the exact limitations of global script code.</p>
<p>The QML <a href="qml-component.html">Component</a> element provides an <i>attached</i> <tt>onCompleted</tt> property that can be used to trigger the execution of script code at startup after the QML environment has been completely established. For example:</p>
<pre class="cpp"> Rectangle {
function startupFunction() {
<span class="comment">// ... startup code</span>
}
Component<span class="operator">.</span>onCompleted: startupFunction();
}</pre>
<p>Any element in a QML file - including nested elements and nested QML component instances - can use this attached property. If there is more than one <tt>onCompleted()</tt> handler to execute at startup, they are run sequentially in an undefined order.</p>
<p>Likewise, the <a href="qml-component.html#onDestruction-signal">Component::onDestruction</a> attached property is triggered on component destruction.</p>
<a name="javascript-and-property-binding"></a>
<h2>JavaScript and Property Binding</h2>
<p>Property bindings can be created in JavaScript by assigning the property with a <tt>function</tt> that returns the required value.</p>
<p>See <a href="propertybinding.html#qml-javascript-assignment">Property Assignment versus Property Binding</a> for details.</p>
<a name="receiving-qml-signals-in-javascript"></a>
<h2>Receiving QML Signals in JavaScript</h2>
<p>To receive a QML signal, use the signal's <tt>connect()</tt> method to connect it to a JavaScript function.</p>
<p>For example, the following code connects the <a href="qml-mousearea.html">MouseArea</a> <tt>clicked</tt> signal to the <tt>jsFunction()</tt> in <tt>script.js</tt>:</p>
<table class="generic">
<tr valign="top" class="odd"><td ><pre class="qml"> import QtQuick 1.0
import "script.js" as MyScript
<span class="type"><a href="qml-item.html">Item</a></span> {
<span class="name">id</span>: <span class="name">item</span>
<span class="name">width</span>: <span class="number">200</span>; <span class="name">height</span>: <span class="number">200</span>
<span class="type"><a href="qml-mousearea.html">MouseArea</a></span> {
<span class="name">id</span>: <span class="name">mouseArea</span>
<span class="name">anchors</span>.fill: <span class="name">parent</span>
}
<span class="name">Component</span>.onCompleted: {
<span class="name">mouseArea</span>.<span class="name">clicked</span>.<span class="name">connect</span>(<span class="name">MyScript</span>.<span class="name">jsFunction</span>)
}
}</pre>
</td><td ><pre class="js"> <span class="comment">// script.js</span>
<span class="keyword">function</span> <span class="name">jsFunction</span>() {
<span class="name">console</span>.<span class="name">log</span>(<span class="string">"Called JavaScript function!"</span>)
}</pre>
</td></tr>
</table>
<p>The <tt>jsFunction()</tt> will now be called whenever <a href="qml-mousearea.html">MouseArea</a>'s <tt>clicked</tt> signal is emitted.</p>
<p>See <a href="qmlevents.html#connecting-signals-to-methods-and-signals">Connecting Signals to Methods and Signals</a> for more information.</p>
<a name="qml-javascript-restrictions"></a>
<h2>QML JavaScript Restrictions</h2>
<p>QML executes standard JavaScript code, with the following restrictions:</p>
<ul>
<li>JavaScript code cannot modify the global object.<p>In QML, the global object is constant - existing properties cannot be modified or deleted, and no new properties may be created.</p>
<p>Most JavaScript programs do not intentionally modify the global object. However, JavaScript's automatic creation of undeclared variables is an implicit modification of the global object, and is prohibited in QML.</p>
<p>Assuming that the <tt>a</tt> variable does not exist in the scope chain, the following code is illegal in QML.</p>
<pre class="cpp"> <span class="comment">// Illegal modification of undeclared variable</span>
a <span class="operator">=</span> <span class="number">1</span>;
<span class="keyword">for</span> (var ii <span class="operator">=</span> <span class="number">1</span>; ii <span class="operator"><</span> <span class="number">10</span>; <span class="operator">+</span><span class="operator">+</span>ii)
a <span class="operator">=</span> a <span class="operator">*</span> ii;
console<span class="operator">.</span>log(<span class="string">"Result: "</span> <span class="operator">+</span> a);</pre>
<p>It can be trivially modified to this legal code.</p>
<pre class="cpp"> var a <span class="operator">=</span> <span class="number">1</span>;
<span class="keyword">for</span> (var ii <span class="operator">=</span> <span class="number">1</span>; ii <span class="operator"><</span> <span class="number">10</span>; <span class="operator">+</span><span class="operator">+</span>ii)
a <span class="operator">=</span> a <span class="operator">*</span> ii;
console<span class="operator">.</span>log(<span class="string">"Result: "</span> <span class="operator">+</span> a);</pre>
<p>Any attempt to modify the global object - either implicitly or explicitly - will cause an exception. If uncaught, this will result in an warning being printed, that includes the file and line number of the offending code.</p>
</li>
<li>Global code is run in a reduced scope<p>During startup, if a QML file includes an external JavaScript file with "global" code, it is executed in a scope that contains only the external file itself and the global object. That is, it will not have access to the QML objects and properties it <a href="qdeclarativescope.html">normally would</a>.</p>
<p>Global code that only accesses script local variable is permitted. This is an example of valid global code.</p>
<pre class="cpp"> var colors <span class="operator">=</span> <span class="operator">[</span> <span class="string">"red"</span><span class="operator">,</span> <span class="string">"blue"</span><span class="operator">,</span> <span class="string">"green"</span><span class="operator">,</span> <span class="string">"orange"</span><span class="operator">,</span> <span class="string">"purple"</span> <span class="operator">]</span>;</pre>
<p>Global code that accesses QML objects will not run correctly.</p>
<pre class="cpp"> <span class="comment">// Invalid global code - the "rootObject" variable is undefined</span>
var initialPosition <span class="operator">=</span> { rootObject<span class="operator">.</span>x<span class="operator">,</span> rootObject<span class="operator">.</span>y }</pre>
<p>This restriction exists as the QML environment is not yet fully established. To run code after the environment setup has completed, refer to <a href="#running-javascript-at-startup">Running JavaScript at Startup</a>.</p>
</li>
<li>The value of <tt>this</tt> is currently undefined in QML in the majority of contexts<p>The <tt>this</tt> keyword is supported when binding properties from JavaScript. In all other situations, the value of <tt>this</tt> is undefined in QML.</p>
<p>To refer to any element, provide an <tt>id</tt>. For example:</p>
<pre class="qml"> <span class="type"><a href="qml-item.html">Item</a></span> {
<span class="name">width</span>: <span class="number">200</span>; <span class="name">height</span>: <span class="number">100</span>
<span class="keyword">function</span> <span class="name">mouseAreaClicked</span>(<span class="name">area</span>) {
<span class="name">console</span>.<span class="name">log</span>(<span class="string">"Clicked in area at: "</span> <span class="operator">+</span> <span class="name">area</span>.<span class="name">x</span> <span class="operator">+</span> <span class="string">", "</span> <span class="operator">+</span> <span class="name">area</span>.<span class="name">y</span>);
}
<span class="comment">// This will not work because this is undefined</span>
<span class="type"><a href="qml-mousearea.html">MouseArea</a></span> {
<span class="name">height</span>: <span class="number">50</span>; <span class="name">width</span>: <span class="number">200</span>
<span class="name">onClicked</span>: <span class="name">mouseAreaClicked</span>(this)
}
<span class="comment">// This will pass area2 to the function</span>
<span class="type"><a href="qml-mousearea.html">MouseArea</a></span> {
<span class="name">id</span>: <span class="name">area2</span>
<span class="name">y</span>: <span class="number">50</span>; <span class="name">height</span>: <span class="number">50</span>; <span class="name">width</span>: <span class="number">200</span>
<span class="name">onClicked</span>: <span class="name">mouseAreaClicked</span>(<span class="name">area2</span>)
}
}</pre>
</li>
</ul>
</div>
<!-- @@@qdeclarativejavascript.html -->
<div class="ft">
<span></span>
</div>
</div>
<div class="footer">
<p>
<acronym title="Copyright">©</acronym> 2012 Nokia Corporation and/or its
subsidiaries. Documentation contributions included herein are the copyrights of
their respective owners.</p>
<br />
<p>
The documentation provided herein is licensed under the terms of the
<a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation
License version 1.3</a> as published by the Free Software Foundation.</p>
<p>
Documentation sources may be obtained from <a href="http://www.qt-project.org">
www.qt-project.org</a>.</p>
<br />
<p>
Nokia, Qt and their respective logos are trademarks of Nokia Corporation
in Finland and/or other countries worldwide. All other trademarks are property
of their respective owners. <a title="Privacy Policy"
href="http://en.gitorious.org/privacy_policy/">Privacy Policy</a></p>
</div>
</body>
</html>
|