1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the documentation of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:FDL$
9 ** GNU Free Documentation License
10 ** Alternatively, this file may be used under the terms of the GNU Free
11 ** Documentation License version 1.3 as published by the Free Software
12 ** Foundation and appearing in the file included in the packaging of
16 ** Alternatively, this file may be used in accordance with the terms
17 ** and conditions contained in a signed written agreement between you
26 ****************************************************************************/
29 \page qml-javascript.html
31 \title JavaScript Expressions in QML
32 \brief adding logic to QML applications with JavaScript
36 This article is a work-in-progress.
40 JavaScript adds logic to QML components. Properties can bind
41 to JavaScript expressions or reside inline in functions or signal handlers. The
42 \l{The QML Engine}{QML engine} will then interpret the expression to calculate new
43 property values or to execute a routine.
45 The \l{JavaScript Runtime}{JavaScript runtime} can run valid standard
46 JavaScript constructs such as conditional operators, arrays, variable setting,
47 loops. In addition to the standard JavaScript properties, the \l {QML Global
48 Object} includes a number of helper methods that simplify building UIs and
49 interacting with the QML environment.
51 The JavaScript environment provided by QML is stricter than that in a web
52 browser. In QML you cannot add, or modify, members of the JavaScript global
53 object. In regular JavaScript, it is possible to do this accidentally by using a
54 variable without declaring it. In QML this will throw an exception, so all local
55 variables should be explicitly declared.
58 \section1 Adding Logic
60 The \l {QML Elements} provide a declarative way of creating and managing the
61 interface layout and scene. Binding properties or signal handlers to JavaScript
62 expressions adds logic to the QML application.
64 Suppose that a button represented by a Rectangle element has a MouseArea and a
65 Text label. The MouseArea will call its \l{MouseArea::}{onPressed} handler when the user presses the defined interactive area. The QML engine will execute the
66 contents bound to the onPressed and onReleased handlers. Typically, a signal
67 handler is bound to JavaScript expressions to initiate other events or to simply
68 assign property values.
73 width: 200; height: 80; color: "lightsteelblue"
80 label.text = "I am Pressed!"
83 label.text = "Click Me!"
90 anchors.centerIn: parent
96 During startup, the QML engine will set up and initialize the property
97 bindings. The JavaScript conditional operator is a valid property binding.
102 width: 200; height: 80;
104 color: mousearea.pressed ? "steelblue" : "lightsteelblue"
113 \section2 Inline JavaScript
115 Small JavaScript functions can be written inline with other QML declarations.
116 These inline functions are added as methods to the QML element that contains
121 function factorial(a) {
126 return a * factorial(a - 1);
131 onClicked: console.log(factorial(10))
136 The factorial function will run whenever the MouseArea detects a clicked signal.
138 As methods, inline functions on the root element in a QML component can be
139 invoked by callers outside the component. If this is not desired, the method
140 can be added to a non-root element or, preferably, written in an external
143 \section2 JavaScript files
145 Large blocks of JavaScript should be written in separate files. These files
146 can be imported into QML files using an \c import statement, in the same way
147 that \l {Modules}{modules} are imported.
149 For example, the \c {factorial()} method in the above example for \l {Inline JavaScript}
150 could be moved into an external file named \c factorial.js, and accessed like this:
153 import "factorial.js" as MathFunctions
157 onClicked: console.log(MathFunctions.factorial(10))
162 For more information about loading external JavaScript files into QML, read
163 the section about \l{Importing JavaScript into QML}.
165 \section1 JavaScript Expressions
166 The \l{JavaScript Runtime}{JavaScript runtime} run regular JavaScript
167 expressions as defined by the
169 \section2 Variables and Properties
173 -values and assigning
174 -relate to property binding
176 \section2 Conditional Loops
178 - conditional operator
180 \section2 Data Structures
183 - relate to the content below about valid JS scope, objects, etc.
184 - more advanced data types such as accessing QML list
187 - function declaration
188 - function assignment (return values)
189 - function parameters
190 - connecting functions
191 - importing libraries, functions
192 - difference between JS functions and signals and QML methods
193 \section3 Receiving QML Signals in JavaScript
195 To receive a QML signal, use the signal's \c connect() method to connect it to a JavaScript
198 For example, the following code connects the MouseArea \c clicked signal to the \c jsFunction()
203 \o \snippet doc/src/snippets/declarative/integrating-javascript/connectjs.qml 0
204 \o \snippet doc/src/snippets/declarative/integrating-javascript/script.js 0
207 The \c jsFunction() will now be called whenever MouseArea's \c clicked signal is emitted.
209 See \l{QML Signal and Handler Event System#Connecting Signals to Methods and Signals}
210 {Connecting Signals to Methods and Signals} for more information.
212 \section2 Advanced Usage
213 - using JS to access QML scene
214 - using JS for algorithms
215 - sorting, reordering lists
216 - how to modify other QML entities with JS
220 \section1 Importing JavaScript into QML
221 Both relative and absolute JavaScript URLs can be imported. In the case of a
222 relative URL, the location is resolved relative to the location of the
223 \l {QML Document} that contains the import. If the script file is not accessible,
224 an error will occur. If the JavaScript needs to be fetched from a network
225 resource, the component's \l {QDeclarativeComponent::status()}{status} is set to
226 "Loading" until the script has been downloaded.
228 Imported JavaScript files are always qualified using the "as" keyword. The
229 qualifier for JavaScript files must be unique, so there is always a one-to-one
230 mapping between qualifiers and JavaScript files. (This also means qualifiers cannot
231 be named the same as built-in JavaScript objects such as \c Date and \c Math).
233 \section2 Importing One JavaScript File From Another
235 If a JavaScript file needs to use functions defined inside another JavaScript file,
236 the other file can be imported using the \l {QML:Qt::include()}{Qt.include()}
237 function. This imports all functions from the other file into the current file's
240 For example, the QML code below left calls \c showCalculations() in \c script.js,
241 which in turn can call \c factorial() in \c factorial.js, as it has included
242 \c factorial.js using \l {QML:Qt::include()}{Qt.include()}.
246 \o {1,2} \snippet doc/src/snippets/declarative/integrating-javascript/includejs/app.qml 0
247 \o \snippet doc/src/snippets/declarative/integrating-javascript/includejs/script.js 0
249 \o \snippet doc/src/snippets/declarative/integrating-javascript/includejs/factorial.js 0
252 Notice that calling \l {QML:Qt::include()}{Qt.include()} imports all functions from
253 \c factorial.js into the \c MyScript namespace, which means the QML component can also
254 access \c factorial() directly as \c MyScript.factorial().
256 In QtQuick 2.0, support has been added to allow JavaScript files to import other
257 JavaScript files and also QML modules using a variation of the standard QML import
258 syntax (where all of the previously described rules and qualifications apply).
260 A JavaScript file may import another in the following fashion:
262 .import "filename.js" as UniqueQualifier
266 .import "factorial.js" as MathFunctions
269 A JavaScript file may import a QML module in the following fashion:
271 .import Module.Name MajorVersion.MinorVersion as UniqueQualifier
275 .import Qt.test 1.0 as JsQtTest
277 In particular, this may be useful in order to access functionality provided
278 via a module API; see qmlRegisterModuleApi() for more information.
280 Due to the ability of a JavaScript file to import another script or QML module in
281 this fashion in QtQuick 2.0, some extra semantics are defined:
283 \o a script with imports will not inherit imports from the QML file which imported it (so accessing Component.error will fail, for example)
284 \o a script without imports will inherit imports from the QML file which imported it (so accessing Component.error will succeed, for example)
285 \o a shared script (i.e., defined as .pragma library) does not inherit imports from any QML file even if it imports no other scripts
288 The first semantic is conceptually correct, given that a particular script
289 might be imported by any number of QML files. The second semantic is retained
290 for the purposes of backwards-compatibility. The third semantic remains
291 unchanged from the current semantics for shared scripts, but is clarified here
292 in respect to the newly possible case (where the script imports other scripts
294 \section2 Code-Behind Implementation Files
296 Most JavaScript files imported into a QML file are stateful implementations
297 for the QML file importing them. In these cases, for QML component instances to
298 behave correctly each instance requires a separate copy of the JavaScript objects
301 The default behavior when importing JavaScript files is to provide a unique, isolated
302 copy for each QML component instance. The code runs in the same scope as the QML
303 component instance and consequently can can access and manipulate the objects and
306 \section2 Stateless JavaScript libraries
308 Some JavaScript files act more like libraries - they provide a set of stateless
309 helper functions that take input and compute output, but never manipulate QML
310 component instances directly.
312 As it would be wasteful for each QML component instance to have a unique copy of
313 these libraries, the JavaScript programmer can indicate a particular file is a
314 stateless library through the use of a pragma, as shown in the following example.
320 function factorial(a) {
325 return a * factorial(a - 1);
329 The pragma declaration must appear before any JavaScript code excluding comments.
331 As they are shared, stateless library files cannot access QML component instance
332 objects or properties directly, although QML values can be passed as function
338 \section1 Running JavaScript at Startup
340 It is occasionally necessary to run some imperative code at application (or
341 component instance) startup. While it is tempting to just include the startup
342 script as \i {global code} in an external script file, this can have severe limitations
343 as the QML environment may not have been fully established. For example, some objects
344 might not have been created or some \l {Property Binding}s may not have been run.
345 \l {QML JavaScript Restrictions} covers the exact limitations of global script code.
347 The QML \l Component element provides an \i attached \c onCompleted property that
348 can be used to trigger the execution of script code at startup after the
349 QML environment has been completely established. For example:
353 function startupFunction() {
357 Component.onCompleted: startupFunction();
361 Any element in a QML file - including nested elements and nested QML component
362 instances - can use this attached property. If there is more than one \c onCompleted()
363 handler to execute at startup, they are run sequentially in an undefined order.
365 Likewise, the \l {Component::onDestruction} attached property is triggered on
366 component destruction.
369 \section1 QML JavaScript Restrictions
371 QML executes standard JavaScript code, with the following restrictions:
374 \o JavaScript code cannot modify the global object.
376 In QML, the global object is constant - existing properties cannot be modified or
377 deleted, and no new properties may be created.
379 Most JavaScript programs do not intentionally modify the global object. However,
380 JavaScript's automatic creation of undeclared variables is an implicit modification
381 of the global object, and is prohibited in QML.
383 Assuming that the \c a variable does not exist in the scope chain, the following code
387 // Illegal modification of undeclared variable
389 for (var ii = 1; ii < 10; ++ii)
391 console.log("Result: " + a);
394 It can be trivially modified to this legal code.
398 for (var ii = 1; ii < 10; ++ii)
400 console.log("Result: " + a);
403 Any attempt to modify the global object - either implicitly or explicitly - will
404 cause an exception. If uncaught, this will result in an warning being printed,
405 that includes the file and line number of the offending code.
407 \o Global code is run in a reduced scope
409 During startup, if a QML file includes an external JavaScript file with "global"
410 code, it is executed in a scope that contains only the external file itself and
411 the global object. That is, it will not have access to the QML objects and
412 properties it \l {QML Scope}{normally would}.
414 Global code that only accesses script local variable is permitted. This is an
415 example of valid global code.
418 var colors = [ "red", "blue", "green", "orange", "purple" ];
421 Global code that accesses QML objects will not run correctly.
424 // Invalid global code - the "rootObject" variable is undefined
425 var initialPosition = { rootObject.x, rootObject.y }
428 This restriction exists as the QML environment is not yet fully established.
429 To run code after the environment setup has completed, refer to
430 \l {Running JavaScript at Startup}.
432 \o The value of \c this is currently undefined in QML in the majority of contexts
434 The \c this keyword is supported when binding properties from JavaScript.
435 In all other situations, the value of
436 \c this is undefined in QML.
438 To refer to any element, provide an \c id. For example:
442 width: 200; height: 100
443 function mouseAreaClicked(area) {
444 console.log("Clicked in area at: " + area.x + ", " + area.y);
446 // This will not work because this is undefined
448 height: 50; width: 200
449 onClicked: mouseAreaClicked(this)
451 // This will pass area2 to the function
454 y: 50; height: 50; width: 200
455 onClicked: mouseAreaClicked(area2)
462 \section1 Scarce Resources in JavaScript
464 As described in the documentation for \l{QML Basic Types}, a \c var type
465 property may hold a "scarce resource" (image or pixmap). There are several
466 important semantics of scarce resources which should be noted:
469 \o By default, a scarce resource is automatically released by the declarative engine as soon as evaluation of the expression in which the scarce resource is allocated is complete if there are no other references to the resource
470 \o A client may explicitly preserve a scarce resource, which will ensure that the resource will not be released until all references to the resource are released and the JavaScript engine runs its garbage collector
471 \o A client may explicitly destroy a scarce resource, which will immediately release the resource
474 In most cases, allowing the engine to automatically release the resource is
475 the correct choice. In some cases, however, this may result in an invalid
476 variant being returned from a function in JavaScript, and in those cases it
477 may be necessary for clients to manually preserve or destroy resources for
480 For the following examples, imagine that we have defined the following class:
482 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/avatarExample.h 0
484 and that we have registered it with the QML type-system as follows:
486 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/avatarExample.cpp 0
488 The AvatarExample class has a property which is a pixmap. When the property
489 is accessed in JavaScript scope, a copy of the resource will be created and
490 stored in a JavaScript object which can then be used within JavaScript. This
491 copy will take up valuable system resources, and so by default the scarce
492 resource copy in the JavaScript object will be released automatically by the
493 declarative engine once evaluation of the JavaScript expression is complete,
494 unless the client explicitly preserves it.
496 \section2 Example One: Automatic Release
498 In the following example, the scarce resource will be automatically released
499 after the binding evaluation is complete.
501 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/exampleOne.qml 0
503 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/avatarExample.cpp 1
505 \section2 Example Two: Automatic Release Prevented By Reference
507 In this example, the resource will not be automatically
508 released after the binding expression evaluation is
509 complete, because there is a property var referencing the
512 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/exampleTwo.qml 0
514 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/avatarExample.cpp 2
516 \section2 Example Three: Explicit Preservation
518 In this example, the resource must be explicitly preserved in order
519 to prevent the declarative engine from automatically releasing the
520 resource after evaluation of the imported script.
522 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/exampleThree.js 0
524 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/exampleThree.qml 0
526 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/avatarExample.cpp 3
528 \section2 Example Four: Explicit Destruction
530 In the following example, we release (via destroy()) an explicitly preserved
531 scarce resource variant. This example shows how a client may free system
532 resources by releasing the scarce resource held in a JavaScript object, if
533 required, during evaluation of a JavaScript expression.
535 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/exampleFour.js 0
537 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/exampleFour.qml 0
539 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/avatarExample.cpp 4
541 \section2 Example Five: Explicit Destruction And JavaScript References
543 One thing to be aware of when using "var" type properties is that they
544 hold references to JavaScript objects. As such, if multiple references
545 to one scarce resource is held, and the client calls destroy() on one
546 of those references (to explicitly release the scarce resource), all of
547 the references will be affected.
549 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/exampleFive.qml 0
551 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/avatarExample.cpp 5