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. See
44 \l{JavaScript Environment Restrictions} for a complete description of the
45 restrictions on JavaScript code executed from QML.
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{Property Attributes}{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{Signal Attributes}{signal handlers} can be defined
69 which are automatically evaluated when the object emits the associated
71 \li \l{Method Attributes}{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 could be moved
248 into an external file named \c factorial.js, and accessed like this:
251 import "factorial.js" as MathFunctions
256 onClicked: console.log(MathFunctions.factorial(10))
261 For more information about loading external JavaScript files into QML, read
262 the section about \l{Importing JavaScript Files in QML Documents}.
266 \section3 Connecting Signals to JavaScript Functions
268 QML object types which emit signals also provide default signal handlers for
269 their signals, as described in a previous section. Sometimes, however, a
270 client will want to cause a signal emitted from one object to trigger a
271 function defined in another object; and in that case, a signal connection
274 A signal emitted by a QML object may be connected to a JavaScript function
275 by calling the signal's \c connect() method and passing the JavaScript function
276 as an argument. For example, the following code connects the MouseArea
277 \c clicked signal to the \c jsFunction() in \c script.js:
281 \li \snippet qml/integrating-javascript/connectjs.qml 0
282 \li \snippet qml/integrating-javascript/script.js 0
285 The \c jsFunction() will now be called whenever MouseArea's \c clicked signal
288 See \l{qtqml-syntax-signals.html}
289 {Connecting Signals to Methods and Signals} for more information.
295 \section1 Running JavaScript at Startup
297 It is occasionally necessary to run some imperative code at application (or
298 component instance) startup. While it is tempting to just include the startup
299 script as \e {global code} in an external script file, this can have severe
300 limitations as the QML environment may not have been fully established. For
301 example, some objects might not have been created or some
302 \l {Property Binding}{property bindings} may not have been run.
303 \l {JavaScript Environment Restrictions} covers the exact limitations of global
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.
335 \section1 Scarce Resources in JavaScript
337 As described in the documentation for \l{QML Basic Types}, a \c var type
338 property may hold a "scarce resource" (image or pixmap). There are several
339 important semantics of scarce resources which should be noted:
342 \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
343 \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
344 \li A client may explicitly destroy a scarce resource, which will immediately release the resource
347 In most cases, allowing the engine to automatically release the resource is
348 the correct choice. In some cases, however, this may result in an invalid
349 variant being returned from a function in JavaScript, and in those cases it
350 may be necessary for clients to manually preserve or destroy resources for
353 For the following examples, imagine that we have defined the following class:
355 \snippet qml/integrating-javascript/scarceresources/avatarExample.h 0
357 and that we have registered it with the QML type-system as follows:
359 \snippet qml/integrating-javascript/scarceresources/avatarExample.cpp 0
361 The AvatarExample class has a property which is a pixmap. When the property
362 is accessed in JavaScript scope, a copy of the resource will be created and
363 stored in a JavaScript object which can then be used within JavaScript. This
364 copy will take up valuable system resources, and so by default the scarce
365 resource copy in the JavaScript object will be released automatically by the
366 declarative engine once evaluation of the JavaScript expression is complete,
367 unless the client explicitly preserves it.
369 \section2 Example One: Automatic Release
371 In the following example, the scarce resource will be automatically released
372 after the binding evaluation is complete.
374 \snippet qml/integrating-javascript/scarceresources/exampleOne.qml 0
376 \snippet qml/integrating-javascript/scarceresources/avatarExample.cpp 1
378 \section2 Example Two: Automatic Release Prevented By Reference
380 In this example, the resource will not be automatically
381 released after the binding expression evaluation is
382 complete, because there is a property var referencing the
385 \snippet qml/integrating-javascript/scarceresources/exampleTwo.qml 0
387 \snippet qml/integrating-javascript/scarceresources/avatarExample.cpp 2
389 \section2 Example Three: Explicit Preservation
391 In this example, the resource must be explicitly preserved in order
392 to prevent the declarative engine from automatically releasing the
393 resource after evaluation of the imported script.
395 \snippet qml/integrating-javascript/scarceresources/exampleThree.js 0
397 \snippet qml/integrating-javascript/scarceresources/exampleThree.qml 0
399 \snippet qml/integrating-javascript/scarceresources/avatarExample.cpp 3
401 \section2 Example Four: Explicit Destruction
403 In the following example, we release (via destroy()) an explicitly preserved
404 scarce resource variant. This example shows how a client may free system
405 resources by releasing the scarce resource held in a JavaScript object, if
406 required, during evaluation of a JavaScript expression.
408 \snippet qml/integrating-javascript/scarceresources/exampleFour.js 0
410 \snippet qml/integrating-javascript/scarceresources/exampleFour.qml 0
412 \snippet qml/integrating-javascript/scarceresources/avatarExample.cpp 4
414 \section2 Example Five: Explicit Destruction and JavaScript References
416 One thing to be aware of when using "var" type properties is that they
417 hold references to JavaScript objects. As such, if multiple references
418 to one scarce resource is held, and the client calls destroy() on one
419 of those references (to explicitly release the scarce resource), all of
420 the references will be affected.
422 \snippet qml/integrating-javascript/scarceresources/exampleFive.qml 0
424 \snippet qml/integrating-javascript/scarceresources/avatarExample.cpp 5