4cc98f1d7a897da0f072ed31c3b92deee0d08e69
[profile/ivi/qtdeclarative.git] / doc / src / qml / javascriptblocks.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 /*!
29 \page qml-javascript.html
30 \ingroup qml-features
31 \title JavaScript Expressions in QML
32 \brief adding logic to QML applications with JavaScript
33
34 \code
35
36 This article is a work-in-progress.
37
38 \endcode
39
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.
44
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.
50
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.
56
57
58 \section1 Adding Logic
59
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.
63
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.
69
70 \code
71 Rectangle {
72     id: button
73     width: 200; height: 80; color: "lightsteelblue"
74
75     MouseArea {
76         id: mousearea
77         anchors.fill: parent
78
79         onPressed: {
80             label.text = "I am Pressed!"
81         }
82         onReleased: {
83             label.text = "Click Me!"
84         }
85
86     }
87
88     Text {
89         id: label
90         anchors.centerIn: parent
91         text: "Press Me!"
92     }
93 }
94 \endcode
95
96 During startup, the QML engine will set up and initialize the property
97 bindings. The JavaScript conditional operator is a valid property binding.
98
99 \code
100 Rectangle {
101     id: colorbutton
102     width: 200; height: 80;
103
104     color: mousearea.pressed ? "steelblue" : "lightsteelblue"
105
106     MouseArea {
107         id: mousearea
108         anchors.fill: parent
109     }
110 }
111 \endcode
112
113 \section2 Inline JavaScript
114
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
117 them.
118
119 \code
120 Item {
121     function factorial(a) {
122         a = parseInt(a);
123         if (a <= 0)
124             return 1;
125         else
126             return a * factorial(a - 1);
127     }
128
129     MouseArea {
130         anchors.fill: parent
131         onClicked: console.log(factorial(10))
132     }
133 }
134 \endcode
135
136 The factorial function will run whenever the MouseArea detects a clicked signal.
137
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
141 JavaScript file.
142
143 \section2 JavaScript files
144
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.
148
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:
151
152 \code
153 import "factorial.js" as MathFunctions
154 Item {
155     MouseArea {
156         anchors.fill: parent
157         onClicked: console.log(MathFunctions.factorial(10))
158     }
159 }
160 \endcode
161
162 For more information about loading external JavaScript files into QML, read
163 the section about \l{Importing JavaScript into QML}.
164
165 \section1 JavaScript Expressions
166 The \l{JavaScript Runtime}{JavaScript runtime} run regular JavaScript
167 expressions as defined by the
168
169 \section2 Variables and Properties
170
171 -variables
172 -basic data types
173 -values and assigning
174 -relate to property binding
175
176 \section2 Conditional Loops
177 - for loops et al.
178 - conditional operator
179
180 \section2 Data Structures
181 - arrays
182 - object
183 - relate to the content below about valid JS scope, objects, etc.
184 - more advanced data types such as accessing QML list
185
186 \section2 Functions
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
194
195 To receive a QML signal, use the signal's \c connect() method to connect it to a JavaScript
196 function.
197
198 For example, the following code connects the MouseArea \c clicked signal to the \c jsFunction()
199 in \c script.js:
200
201 \table
202 \row
203 \o \snippet doc/src/snippets/declarative/integrating-javascript/connectjs.qml 0
204 \o \snippet doc/src/snippets/declarative/integrating-javascript/script.js 0
205 \endtable
206
207 The \c jsFunction() will now be called whenever MouseArea's \c clicked signal is emitted.
208
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.
211
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
217
218
219
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.
227
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).
232
233 \section2 Importing One JavaScript File From Another
234
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
238 namespace.
239
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()}.
243
244 \table
245 \row
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
248 \row
249 \o \snippet doc/src/snippets/declarative/integrating-javascript/includejs/factorial.js 0
250 \endtable
251
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().
255
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).
259
260 A JavaScript file may import another in the following fashion:
261 \code
262 .import "filename.js" as UniqueQualifier
263 \endcode
264 For example:
265 \code
266 .import "factorial.js" as MathFunctions
267 \endcode
268
269 A JavaScript file may import a QML module in the following fashion:
270 \code
271 .import Module.Name MajorVersion.MinorVersion as UniqueQualifier
272 \endcode
273 For example:
274 \code
275 .import Qt.test 1.0 as JsQtTest
276 \endcode
277 In particular, this may be useful in order to access functionality provided
278 via a module API; see qmlRegisterModuleApi() for more information.
279
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:
282 \list
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
286 \endlist
287
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
293 or modules).
294 \section2 Code-Behind Implementation Files
295
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
299 and state.
300
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
304 properties declared.
305
306 \section2 Stateless JavaScript libraries
307
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.
311
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.
315
316 \code
317 // factorial.js
318 .pragma library
319
320 function factorial(a) {
321     a = parseInt(a);
322     if (a <= 0)
323         return 1;
324     else
325         return a * factorial(a - 1);
326 }
327 \endcode
328
329 The pragma declaration must appear before any JavaScript code excluding comments.
330
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
333 parameters.
334
335
336
337
338 \section1 Running JavaScript at Startup
339
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.
346
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:
350
351 \code
352 Rectangle {
353     function startupFunction() {
354         // ... startup code
355     }
356
357     Component.onCompleted: startupFunction();
358 }
359 \endcode
360
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.
364
365 Likewise, the \l {Component::onDestruction} attached property is triggered on
366 component destruction.
367
368
369 \section1 QML JavaScript Restrictions
370
371 QML executes standard JavaScript code, with the following restrictions:
372
373 \list
374 \o JavaScript code cannot modify the global object.
375
376 In QML, the global object is constant - existing properties cannot be modified or
377 deleted, and no new properties may be created.
378
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.
382
383 Assuming that the \c a variable does not exist in the scope chain, the following code
384 is illegal in QML.
385
386 \code
387 // Illegal modification of undeclared variable
388 a = 1;
389 for (var ii = 1; ii < 10; ++ii)
390     a = a * ii;
391 console.log("Result: " + a);
392 \endcode
393
394 It can be trivially modified to this legal code.
395
396 \code
397 var a = 1;
398 for (var ii = 1; ii < 10; ++ii)
399     a = a * ii;
400 console.log("Result: " + a);
401 \endcode
402
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.
406
407 \o Global code is run in a reduced scope
408
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}.
413
414 Global code that only accesses script local variable is permitted.  This is an
415 example of valid global code.
416
417 \code
418 var colors = [ "red", "blue", "green", "orange", "purple" ];
419 \endcode
420
421 Global code that accesses QML objects will not run correctly.
422
423 \code
424 // Invalid global code - the "rootObject" variable is undefined
425 var initialPosition = { rootObject.x, rootObject.y }
426 \endcode
427
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}.
431
432 \o The value of \c this is currently undefined in QML in the majority of contexts
433
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.
437
438 To refer to any element, provide an \c id.  For example:
439
440 \qml
441 Item {
442     width: 200; height: 100
443     function mouseAreaClicked(area) {
444         console.log("Clicked in area at: " + area.x + ", " + area.y);
445     }
446     // This will not work because this is undefined
447     MouseArea {
448         height: 50; width: 200
449         onClicked: mouseAreaClicked(this)
450     }
451     // This will pass area2 to the function
452     MouseArea {
453         id: area2
454         y: 50; height: 50; width: 200
455         onClicked: mouseAreaClicked(area2)
456     }
457 }
458 \endqml
459
460 \endlist
461
462 \section1 Scarce Resources in JavaScript
463
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:
467
468 \list
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
472 \endlist
473
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
478 themselves.
479
480 For the following examples, imagine that we have defined the following class:
481
482 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/avatarExample.h 0
483
484 and that we have registered it with the QML type-system as follows:
485
486 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/avatarExample.cpp 0
487
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.
495
496 \section2 Example One: Automatic Release
497
498 In the following example, the scarce resource will be automatically released
499 after the binding evaluation is complete.
500
501 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/exampleOne.qml 0
502
503 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/avatarExample.cpp 1
504
505 \section2 Example Two: Automatic Release Prevented By Reference
506
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
510 scarce resource.
511
512 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/exampleTwo.qml 0
513
514 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/avatarExample.cpp 2
515
516 \section2 Example Three: Explicit Preservation
517
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.
521
522 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/exampleThree.js 0
523
524 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/exampleThree.qml 0
525
526 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/avatarExample.cpp 3
527
528 \section2 Example Four: Explicit Destruction
529
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.
534
535 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/exampleFour.js 0
536
537 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/exampleFour.qml 0
538
539 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/avatarExample.cpp 4
540
541 \section2 Example Five: Explicit Destruction And JavaScript References
542
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.
548
549 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/exampleFive.qml 0
550
551 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/avatarExample.cpp 5
552
553 */