Make title capitalization more consistent in QML documentation.
[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.  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}.
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{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
67       effect
68   \li \l{QML Object Attributes#signal-handlers}{signal handlers} can be defined
69       which are automatically evaluated when the object emits the associated
70       signal
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
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 for
248 \l{JavaScript Expressions in Custom Methods} could be moved into an external
249 file named \c factorial.js, and accessed like this:
250
251 \qml
252 import "factorial.js" as MathFunctions
253
254 Item {
255     MouseArea {
256         anchors.fill: parent
257         onClicked: console.log(MathFunctions.factorial(10))
258     }
259 }
260 \endqml
261
262 For more information about loading external JavaScript files into QML, read
263 the section about \l{Importing JavaScript into QML}.
264
265
266
267 \section3 Connecting Signals to JavaScript Functions
268
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
273 is often preferable.
274
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:
279
280 \table
281 \row
282 \li \snippet qml/integrating-javascript/connectjs.qml 0
283 \li \snippet qml/integrating-javascript/script.js 0
284 \endtable
285
286 The \c jsFunction() will now be called whenever MouseArea's \c clicked signal
287 is emitted.
288
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.
291
292
293
294
295
296 \section1 Running JavaScript at Startup
297
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.
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
336
337
338 \section1 JavaScript Expression Restrictions in QML
339
340 QML executes standard JavaScript code, with the following restrictions:
341
342 \list
343 \li JavaScript code cannot modify the global object.
344
345 In QML, the global object is constant - existing properties cannot be modified
346 or deleted, and no new properties may be created.
347
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.
351
352 Assuming that the \c a variable does not exist in the scope chain, the
353 following code is illegal in QML:
354
355 \code
356 // Illegal modification of undeclared variable
357 a = 1;
358 for (var ii = 1; ii < 10; ++ii)
359     a = a * ii;
360 console.log("Result: " + a);
361 \endcode
362
363 It can be trivially modified to this legal code.
364
365 \code
366 var a = 1;
367 for (var ii = 1; ii < 10; ++ii)
368     a = a * ii;
369 console.log("Result: " + a);
370 \endcode
371
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.
375
376 \li Global code is run in a reduced scope
377
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}.
382
383 Global code that only accesses script local variable is permitted.  This is an
384 example of valid global code.
385
386 \code
387 var colors = [ "red", "blue", "green", "orange", "purple" ];
388 \endcode
389
390 Global code that accesses QML objects will not run correctly.
391
392 \code
393 // Invalid global code - the "rootObject" variable is undefined
394 var initialPosition = { rootObject.x, rootObject.y }
395 \endcode
396
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}.
400
401 \li The value of \c this is currently undefined in QML in the majority of contexts
402
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.
406
407 To refer to any element, provide an \c id.  For example:
408
409 \qml
410 Item {
411     width: 200; height: 100
412     function mouseAreaClicked(area) {
413         console.log("Clicked in area at: " + area.x + ", " + area.y);
414     }
415     // This will not work because this is undefined
416     MouseArea {
417         height: 50; width: 200
418         onClicked: mouseAreaClicked(this)
419     }
420     // This will pass area2 to the function
421     MouseArea {
422         id: area2
423         y: 50; height: 50; width: 200
424         onClicked: mouseAreaClicked(area2)
425     }
426 }
427 \endqml
428
429 \endlist
430
431 \section1 Scarce Resources in JavaScript
432
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:
436
437 \list
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
441 \endlist
442
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
447 themselves.
448
449 For the following examples, imagine that we have defined the following class:
450
451 \snippet qml/integrating-javascript/scarceresources/avatarExample.h 0
452
453 and that we have registered it with the QML type-system as follows:
454
455 \snippet qml/integrating-javascript/scarceresources/avatarExample.cpp 0
456
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.
464
465 \section2 Example One: Automatic Release
466
467 In the following example, the scarce resource will be automatically released
468 after the binding evaluation is complete.
469
470 \snippet qml/integrating-javascript/scarceresources/exampleOne.qml 0
471
472 \snippet qml/integrating-javascript/scarceresources/avatarExample.cpp 1
473
474 \section2 Example Two: Automatic Release Prevented By Reference
475
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
479 scarce resource.
480
481 \snippet qml/integrating-javascript/scarceresources/exampleTwo.qml 0
482
483 \snippet qml/integrating-javascript/scarceresources/avatarExample.cpp 2
484
485 \section2 Example Three: Explicit Preservation
486
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.
490
491 \snippet qml/integrating-javascript/scarceresources/exampleThree.js 0
492
493 \snippet qml/integrating-javascript/scarceresources/exampleThree.qml 0
494
495 \snippet qml/integrating-javascript/scarceresources/avatarExample.cpp 3
496
497 \section2 Example Four: Explicit Destruction
498
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.
503
504 \snippet qml/integrating-javascript/scarceresources/exampleFour.js 0
505
506 \snippet qml/integrating-javascript/scarceresources/exampleFour.qml 0
507
508 \snippet qml/integrating-javascript/scarceresources/avatarExample.cpp 4
509
510 \section2 Example Five: Explicit Destruction and JavaScript References
511
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.
517
518 \snippet qml/integrating-javascript/scarceresources/exampleFive.qml 0
519
520 \snippet qml/integrating-javascript/scarceresources/avatarExample.cpp 5
521
522 */