Update to 5.0.0-beta1
[profile/ivi/qtdeclarative.git] / src / qml / doc / src / javascript / expressions.qdoc
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
5 **
6 ** This file is part of the documentation of the Qt Toolkit.
7 **
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
13 ** this file.
14 **
15 ** Other Usage
16 ** Alternatively, this file may be used in accordance with the terms
17 ** and conditions contained in a signed written agreement between you
18 ** and Nokia.
19 **
20 **
21 **
22 **
23 **
24 ** $QT_END_LICENSE$
25 **
26 ****************************************************************************/
27 /*!
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
31
32
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.
38
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.
46
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
49 JavaScript imports.
50
51
52
53
54 \section1 JavaScript Expressions in QML Objects
55
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:
59
60 \list
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
67       effect
68   \li \l{Signal Attributes}{signal handlers} can be defined
69       which are automatically evaluated when the object emits the associated
70       signal
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
75       document
76 \endlist
77
78
79
80 \section2 Property Bindings
81
82 During startup, the QML engine will set up and initialize the property
83 bindings. The JavaScript conditional operator is a valid property binding.
84
85 \qml
86 import QtQuick 2.0
87
88 Rectangle {
89     id: colorbutton
90     width: 200; height: 80;
91
92     color: mousearea.pressed ? "steelblue" : "lightsteelblue"
93
94     MouseArea {
95         id: mousearea
96         anchors.fill: parent
97     }
98 }
99 \endqml
100
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.
104
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:
110
111 \qml
112 import QtQuick 2.0
113
114 Rectangle {
115     id: colorbutton
116     width: 200; height: 80;
117
118     color: "red"
119
120     MouseArea {
121         id: mousearea
122         anchors.fill: parent
123     }
124
125     Component.onCompleted: {
126         color = Qt.binding(function() { return mousearea.pressed ? "steelblue" : "lightsteelblue" });
127     }
128 }
129 \endqml
130
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.
136
137
138
139 \section2 Signal Handlers
140
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.
144
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
152 values.
153
154 \qml
155 import QtQuick 2.0
156
157 Rectangle {
158     id: button
159     width: 200; height: 80; color: "lightsteelblue"
160
161     MouseArea {
162         id: mousearea
163         anchors.fill: parent
164
165         onPressed: {
166             // arbitrary JavaScript expression
167             label.text = "I am Pressed!"
168         }
169         onReleased: {
170             // arbitrary JavaScript expression
171             label.text = "Click Me!"
172         }
173
174     }
175
176     Text {
177         id: label
178         anchors.centerIn: parent
179         text: "Press Me!"
180     }
181 }
182 \endqml
183
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.
188
189
190
191 \section2 JavaScript Expressions in Functions
192
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.
196
197
198
199 \section3 Custom Methods
200
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.
206
207 An example of an inline custom method is as follows:
208
209 \qml
210 import QtQuick 2.0
211
212 Item {
213     function factorial(a) {
214         a = parseInt(a);
215         if (a <= 0)
216             return 1;
217         else
218             return a * factorial(a - 1);
219     }
220
221     MouseArea {
222         anchors.fill: parent
223         onClicked: console.log(factorial(10))
224     }
225 }
226 \endqml
227
228 The factorial function will run whenever the MouseArea detects a clicked signal.
229
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.
235
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.
238
239
240
241 \section3 Functions in Imported JavaScript Files
242
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.
246
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:
249
250 \qml
251 import "factorial.js" as MathFunctions
252
253 Item {
254     MouseArea {
255         anchors.fill: parent
256         onClicked: console.log(MathFunctions.factorial(10))
257     }
258 }
259 \endqml
260
261 For more information about loading external JavaScript files into QML, read
262 the section about \l{Importing JavaScript Files in QML Documents}.
263
264
265
266 \section3 Connecting Signals to JavaScript Functions
267
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
272 is often preferable.
273
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:
278
279 \table
280 \row
281 \li \snippet qml/integrating-javascript/connectjs.qml 0
282 \li \snippet qml/integrating-javascript/script.js 0
283 \endtable
284
285 The \c jsFunction() will now be called whenever MouseArea's \c clicked signal
286 is emitted.
287
288 See \l{qtqml-syntax-signals.html}
289 {Connecting Signals to Methods and Signals} for more information.
290
291
292
293
294
295 \section1 Running JavaScript at Startup
296
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
304 script code.
305
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:
312
313 \qml
314 import QtQuick 2.0
315
316 Rectangle {
317     function startupFunction() {
318         // ... startup code
319     }
320
321     Component.onCompleted: startupFunction();
322 }
323 \endqml
324
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
328 an undefined order.
329
330 Likewise, the \l {Component::onDestruction} handler definitions are triggered
331 on component destruction.
332
333
334
335 \section1 Scarce Resources in JavaScript
336
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:
340
341 \list
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
345 \endlist
346
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
351 themselves.
352
353 For the following examples, imagine that we have defined the following class:
354
355 \snippet qml/integrating-javascript/scarceresources/avatarExample.h 0
356
357 and that we have registered it with the QML type-system as follows:
358
359 \snippet qml/integrating-javascript/scarceresources/avatarExample.cpp 0
360
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.
368
369 \section2 Example One: Automatic Release
370
371 In the following example, the scarce resource will be automatically released
372 after the binding evaluation is complete.
373
374 \snippet qml/integrating-javascript/scarceresources/exampleOne.qml 0
375
376 \snippet qml/integrating-javascript/scarceresources/avatarExample.cpp 1
377
378 \section2 Example Two: Automatic Release Prevented By Reference
379
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
383 scarce resource.
384
385 \snippet qml/integrating-javascript/scarceresources/exampleTwo.qml 0
386
387 \snippet qml/integrating-javascript/scarceresources/avatarExample.cpp 2
388
389 \section2 Example Three: Explicit Preservation
390
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.
394
395 \snippet qml/integrating-javascript/scarceresources/exampleThree.js 0
396
397 \snippet qml/integrating-javascript/scarceresources/exampleThree.qml 0
398
399 \snippet qml/integrating-javascript/scarceresources/avatarExample.cpp 3
400
401 \section2 Example Four: Explicit Destruction
402
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.
407
408 \snippet qml/integrating-javascript/scarceresources/exampleFour.js 0
409
410 \snippet qml/integrating-javascript/scarceresources/exampleFour.qml 0
411
412 \snippet qml/integrating-javascript/scarceresources/avatarExample.cpp 4
413
414 \section2 Example Five: Explicit Destruction and JavaScript References
415
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.
421
422 \snippet qml/integrating-javascript/scarceresources/exampleFive.qml 0
423
424 \snippet qml/integrating-javascript/scarceresources/avatarExample.cpp 5
425
426 */