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 ****************************************************************************/
28 \page qtqml-javascript-expressions.html
29 \title JavaScript Expressions in QML Documents
30 \brief Description of where JavaScript expressions are valid in QML documents
33 The \l{JavaScript Host Environment} provided by QML can run valid standard
34 JavaScript constructs such as conditional operators, arrays, variable setting,
35 loops. In addition to the standard JavaScript properties, the \l {QML Global
36 Object} includes a number of helper methods that simplify building UIs and
37 interacting with the QML environment.
39 The JavaScript environment provided by QML is stricter than that in a web
40 browser. For example, in QML you cannot add, or modify, members of the
41 JavaScript global object. In regular JavaScript, it is possible to do this
42 accidentally by using a variable without declaring it. In QML this will throw
43 an exception, so all local variables should be explicitly declared. A complete
44 description of the limitations of JavaScript code in QML is included in an
45 \l{JavaScript Expression Restrictions in QML}{upcoming section}.
47 There are various ways in which JavaScript expressions may be defined and used
48 in QML, including property bindings, signal handlers, custom methods and
54 \section1 JavaScript Expressions in QML Objects
56 QML \l{QML Object Types}{object types} defined in \l{QML Documents}
57 {QML documents} can make use of JavaScript expressions which implement program
58 logic. There are four ways that JavaScript can be used in a QML document:
61 \li \l{QML Object Attributes#property-initialization}{properties} can be
62 assigned \l{Property Binding}{bindings} which are defined with
63 JavaScript expressions, and which are automatically evaluated by the
64 \l{QQmlEngine}{QML engine} when any properties accessed in the binding
65 change, in order to ensure always-up-to-date property values. Binding
66 expressions can also perform function evaluation as an explicit side
68 \li \l{QML Object Attributes#signal-handlers}{signal handlers} can be defined
69 which are automatically evaluated when the object emits the associated
71 \li \l{QML Object Attributes#custom-methods}{custom methods} can be defined
72 in QML files as JavaScript functions
73 \li JavaScript files providing functions and variables can be
74 \l{Importing JavaScript Files in QML Documents}{imported} in a QML
80 \section2 Property Bindings
82 During startup, the QML engine will set up and initialize the property
83 bindings. The JavaScript conditional operator is a valid property binding.
90 width: 200; height: 80;
92 color: mousearea.pressed ? "steelblue" : "lightsteelblue"
101 In fact, any JavaScript expression (no matter how complex) may be used in a
102 property binding definition, as long as the result of the expression is a
103 value whose type can be assigned to the property.
105 There are two ways to define a property binding: the first (and most common)
106 is, as previously shown, in a \l{QML Object Attributes#property-initialization}
107 {property initialization}. The second (and much rarer) way is to assign the
108 property a function returned from the \l{Qt::binding()}{Qt.binding()} function,
109 from within imperative JavaScript code, as shown below:
116 width: 200; height: 80;
125 Component.onCompleted: {
126 color = Qt.binding(function() { return mousearea.pressed ? "steelblue" : "lightsteelblue" });
131 See the \l{Property Binding}{property bindings} documentation for more
132 information about how to define property bindings, and see the documentation
133 about \l{qml-javascript-assignment}
134 {Property Assignment versus Property Binding} for information about how
135 bindings differ from value assignments.
139 \section2 Signal Handlers
141 QML object types can emit signals in reaction to certain events occurring.
142 Those signals can be handled by signal handler functions, which can be defined
143 by clients to implement custom program logic.
145 Suppose that a button represented by a Rectangle element has a MouseArea and a
146 Text label. The MouseArea will emit its "pressed" signal when the user presses
147 the defined interactive area, which will automatically trigger the
148 \l{MouseArea::}{onPressed} handler, which can be defined by clients. The QML
149 engine will execute the JavaScript expressions defined in the onPressed and
150 onReleased handlers, as required. Typically, a signal handler is bound to
151 JavaScript expressions to initiate other events or to simply assign property
159 width: 200; height: 80; color: "lightsteelblue"
166 // arbitrary JavaScript expression
167 label.text = "I am Pressed!"
170 // arbitrary JavaScript expression
171 label.text = "Click Me!"
178 anchors.centerIn: parent
184 Please see the \l{Signal and Handler Event System} documentation for in-depth
185 discussion of signals and signal handlers, and see the
186 \l{QML Object Attributes} documentation for in-depth discussion of how
187 to define the implementation of signal handlers in QML with JavaScript.
191 \section2 JavaScript Expressions in Functions
193 Program logic can also be defined in JavaScript functions. These functions can
194 be defined inline in QML documents (as custom methods) or externally in
195 imported JavaScript files.
199 \section3 Custom Methods
201 Custom methods can be defined in QML documents and may be called from signal
202 handlers, property bindings, or functions in other QML objects. Methods
203 defined in this way are often referred to as "inline JavaScript functions" as
204 their implementation is included in the QML object type definition
205 (QML document), as opposed to an external JavaScript file.
207 An example of an inline custom method is as follows:
213 function factorial(a) {
218 return a * factorial(a - 1);
223 onClicked: console.log(factorial(10))
228 The factorial function will run whenever the MouseArea detects a clicked signal.
230 Importantly, custom methods defined inline in a QML document are exposed to
231 other objects, and therefore inline functions on the root object in a QML
232 component can be invoked by callers outside the component. If this is not
233 desired, the method can be added to a non-root object or, preferably, written
234 in an external JavaScript file.
236 See the \l{QML Object Attributes} documentation for in-depth discussion of how
237 to define custom methods in QML with JavaScript code implementations.
241 \section3 Functions in Imported JavaScript Files
243 Non-trivial program logic is best separated into external JavaScript files.
244 These files can be imported into QML files using an \c import statement, in
245 the same way that \l {QML Modules}{modules} are imported.
247 For example, the \c {factorial()} method in the above example for
248 \l{JavaScript Expressions in Custom Methods} could be moved into an external
249 file named \c factorial.js, and accessed like this:
252 import "factorial.js" as MathFunctions
257 onClicked: console.log(MathFunctions.factorial(10))
262 For more information about loading external JavaScript files into QML, read
263 the section about \l{Importing JavaScript into QML}.
267 \section3 Connecting Signals to JavaScript Functions
269 QML object types which emit signals also provide default signal handlers for
270 their signals, as described in a previous section. Sometimes, however, a
271 client will want to cause a signal emitted from one object to trigger a
272 function defined in another object; and in that case, a signal connection
275 A signal emitted by a QML object may be connected to a JavaScript function
276 by calling the signal's \c connect() method and passing the JavaScript function
277 as an argument. For example, the following code connects the MouseArea
278 \c clicked signal to the \c jsFunction() in \c script.js:
282 \li \snippet qml/integrating-javascript/connectjs.qml 0
283 \li \snippet qml/integrating-javascript/script.js 0
286 The \c jsFunction() will now be called whenever MouseArea's \c clicked signal
289 See \l{QML Signal and Handler Event System#Connecting Signals to Methods and Signals}
290 {Connecting Signals to Methods and Signals} for more information.
296 \section1 Running JavaScript at Startup
298 It is occasionally necessary to run some imperative code at application (or
299 component instance) startup. While it is tempting to just include the startup
300 script as \e {global code} in an external script file, this can have severe
301 limitations as the QML environment may not have been fully established. For
302 example, some objects might not have been created or some
303 \l {Property Binding}s may not have been run. \l {QML JavaScript Restrictions}
304 covers the exact limitations of global script code.
306 Every QML object has an \e attached \l Component property that references the
307 component within which the object was instantiated. Every \l Component
308 will emit a \c completed signal, and thus every object can define an
309 implementation for the \c onCompleted() handler which can be used to trigger the
310 execution of script code at startup after the QML environment has been
311 completely established. For example:
317 function startupFunction() {
321 Component.onCompleted: startupFunction();
325 Any object in a QML file - including nested objects and nested QML component
326 instances - can use this attached property. If there is more than one
327 \c onCompleted() handler to execute at startup, they are run sequentially in
330 Likewise, the \l {Component::onDestruction} handler definitions are triggered
331 on component destruction.
338 \section1 JavaScript Expression Restrictions in QML
340 QML executes standard JavaScript code, with the following restrictions:
343 \li JavaScript code cannot modify the global object.
345 In QML, the global object is constant - existing properties cannot be modified
346 or deleted, and no new properties may be created.
348 Most JavaScript programs do not intentionally modify the global object.
349 However, JavaScript's automatic creation of undeclared variables is an implicit
350 modification of the global object, and is prohibited in QML.
352 Assuming that the \c a variable does not exist in the scope chain, the
353 following code is illegal in QML:
356 // Illegal modification of undeclared variable
358 for (var ii = 1; ii < 10; ++ii)
360 console.log("Result: " + a);
363 It can be trivially modified to this legal code.
367 for (var ii = 1; ii < 10; ++ii)
369 console.log("Result: " + a);
372 Any attempt to modify the global object - either implicitly or explicitly - will
373 cause an exception. If uncaught, this will result in an warning being printed,
374 that includes the file and line number of the offending code.
376 \li Global code is run in a reduced scope
378 During startup, if a QML file includes an external JavaScript file with "global"
379 code, it is executed in a scope that contains only the external file itself and
380 the global object. That is, it will not have access to the QML objects and
381 properties it \l {QML Scope}{normally would}.
383 Global code that only accesses script local variable is permitted. This is an
384 example of valid global code.
387 var colors = [ "red", "blue", "green", "orange", "purple" ];
390 Global code that accesses QML objects will not run correctly.
393 // Invalid global code - the "rootObject" variable is undefined
394 var initialPosition = { rootObject.x, rootObject.y }
397 This restriction exists as the QML environment is not yet fully established.
398 To run code after the environment setup has completed, refer to
399 \l {Running JavaScript at Startup}.
401 \li The value of \c this is currently undefined in QML in the majority of contexts
403 The \c this keyword is supported when binding properties from JavaScript.
404 In all other situations, the value of
405 \c this is undefined in QML.
407 To refer to any element, provide an \c id. For example:
411 width: 200; height: 100
412 function mouseAreaClicked(area) {
413 console.log("Clicked in area at: " + area.x + ", " + area.y);
415 // This will not work because this is undefined
417 height: 50; width: 200
418 onClicked: mouseAreaClicked(this)
420 // This will pass area2 to the function
423 y: 50; height: 50; width: 200
424 onClicked: mouseAreaClicked(area2)
431 \section1 Scarce Resources in JavaScript
433 As described in the documentation for \l{QML Basic Types}, a \c var type
434 property may hold a "scarce resource" (image or pixmap). There are several
435 important semantics of scarce resources which should be noted:
438 \li 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
439 \li 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
440 \li A client may explicitly destroy a scarce resource, which will immediately release the resource
443 In most cases, allowing the engine to automatically release the resource is
444 the correct choice. In some cases, however, this may result in an invalid
445 variant being returned from a function in JavaScript, and in those cases it
446 may be necessary for clients to manually preserve or destroy resources for
449 For the following examples, imagine that we have defined the following class:
451 \snippet qml/integrating-javascript/scarceresources/avatarExample.h 0
453 and that we have registered it with the QML type-system as follows:
455 \snippet qml/integrating-javascript/scarceresources/avatarExample.cpp 0
457 The AvatarExample class has a property which is a pixmap. When the property
458 is accessed in JavaScript scope, a copy of the resource will be created and
459 stored in a JavaScript object which can then be used within JavaScript. This
460 copy will take up valuable system resources, and so by default the scarce
461 resource copy in the JavaScript object will be released automatically by the
462 declarative engine once evaluation of the JavaScript expression is complete,
463 unless the client explicitly preserves it.
465 \section2 Example One: Automatic Release
467 In the following example, the scarce resource will be automatically released
468 after the binding evaluation is complete.
470 \snippet qml/integrating-javascript/scarceresources/exampleOne.qml 0
472 \snippet qml/integrating-javascript/scarceresources/avatarExample.cpp 1
474 \section2 Example Two: Automatic Release Prevented By Reference
476 In this example, the resource will not be automatically
477 released after the binding expression evaluation is
478 complete, because there is a property var referencing the
481 \snippet qml/integrating-javascript/scarceresources/exampleTwo.qml 0
483 \snippet qml/integrating-javascript/scarceresources/avatarExample.cpp 2
485 \section2 Example Three: Explicit Preservation
487 In this example, the resource must be explicitly preserved in order
488 to prevent the declarative engine from automatically releasing the
489 resource after evaluation of the imported script.
491 \snippet qml/integrating-javascript/scarceresources/exampleThree.js 0
493 \snippet qml/integrating-javascript/scarceresources/exampleThree.qml 0
495 \snippet qml/integrating-javascript/scarceresources/avatarExample.cpp 3
497 \section2 Example Four: Explicit Destruction
499 In the following example, we release (via destroy()) an explicitly preserved
500 scarce resource variant. This example shows how a client may free system
501 resources by releasing the scarce resource held in a JavaScript object, if
502 required, during evaluation of a JavaScript expression.
504 \snippet qml/integrating-javascript/scarceresources/exampleFour.js 0
506 \snippet qml/integrating-javascript/scarceresources/exampleFour.qml 0
508 \snippet qml/integrating-javascript/scarceresources/avatarExample.cpp 4
510 \section2 Example Five: Explicit Destruction and JavaScript References
512 One thing to be aware of when using "var" type properties is that they
513 hold references to JavaScript objects. As such, if multiple references
514 to one scarce resource is held, and the client calls destroy() on one
515 of those references (to explicitly release the scarce resource), all of
516 the references will be affected.
518 \snippet qml/integrating-javascript/scarceresources/exampleFive.qml 0
520 \snippet qml/integrating-javascript/scarceresources/avatarExample.cpp 5