Remove "All rights reserved" line from license headers.
[profile/ivi/qtdeclarative.git] / doc / src / qtquick1 / 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 qdeclarativejavascript.html
30 \inqmlmodule QtQuick 1
31 \title Integrating JavaScript
32
33 QML encourages building UIs declaratively, using \l {Property Binding} and the
34 composition of existing \l {QML Elements}.  To allow the implementation of more
35 advanced behavior, QML integrates tightly with imperative JavaScript code.
36
37 The JavaScript environment provided by QML is stricter than that in a web browser.
38 In QML you cannot add, or modify, members of the JavaScript global object.  It
39 is possible to do this accidentally by using a variable without declaring it.  In
40 QML this will throw an exception, so all local variables should be explicitly
41 declared.
42
43 In addition to the standard JavaScript properties, the \l {QML Global Object}
44 includes a number of helper methods that simplify building UIs and interacting
45 with the QML environment.
46
47 \section1 Inline JavaScript
48
49 Small JavaScript functions can be written inline with other QML declarations.
50 These inline functions are added as methods to the QML element that contains
51 them.
52
53 \code
54 Item {
55     function factorial(a) {
56         a = parseInt(a);
57         if (a <= 0)
58             return 1;
59         else
60             return a * factorial(a - 1);
61     }
62
63     MouseArea {
64         anchors.fill: parent
65         onClicked: console.log(factorial(10))
66     }
67 }
68 \endcode
69
70 As methods, inline functions on the root element in a QML component can be
71 invoked by callers outside the component.  If this is not desired, the method
72 can be added to a non-root element or, preferably, written in an external
73 JavaScript file.
74
75 \section1 Separate JavaScript files
76
77 Large blocks of JavaScript should be written in separate files. These files
78 can be imported into QML files using an \c import statement, in the same way
79 that \l {Modules}{modules} are imported.
80
81 For example, the \c {factorial()} method in the above example for \l {Inline JavaScript}
82 could be moved into an external file named \c factorial.js, and accessed like this:
83
84 \code
85 import "factorial.js" as MathFunctions
86 Item {
87     MouseArea {
88         anchors.fill: parent
89         onClicked: console.log(MathFunctions.factorial(10))
90     }
91 }
92 \endcode
93
94 Both relative and absolute JavaScript URLs can be imported.  In the case of a
95 relative URL, the location is resolved relative to the location of the
96 \l {QML Document} that contains the import.  If the script file is not accessible,
97 an error will occur.  If the JavaScript needs to be fetched from a network
98 resource, the component's \l {QDeclarativeComponent::status()}{status} is set to
99 "Loading" until the script has been downloaded.
100
101 Imported JavaScript files are always qualified using the "as" keyword.  The
102 qualifier for JavaScript files must be unique, so there is always a one-to-one
103 mapping between qualifiers and JavaScript files. (This also means qualifiers cannot
104 be named the same as built-in JavaScript objects such as \c Date and \c Math).
105
106
107 \section2 Code-Behind Implementation Files
108
109 Most JavaScript files imported into a QML file are stateful, logic implementations
110 for the QML file importing them.  In these cases, for QML component instances to
111 behave correctly each instance requires a separate copy of the JavaScript objects
112 and state.
113
114 The default behavior when importing JavaScript files is to provide a unique, isolated
115 copy for each QML component instance.  The code runs in the same scope as the QML
116 component instance and consequently can can access and manipulate the objects and
117 properties declared.
118
119 \section2 Stateless JavaScript libraries
120
121 Some JavaScript files act more like libraries - they provide a set of stateless
122 helper functions that take input and compute output, but never manipulate QML
123 component instances directly.
124
125 As it would be wasteful for each QML component instance to have a unique copy of
126 these libraries, the JavaScript programmer can indicate a particular file is a
127 stateless library through the use of a pragma, as shown in the following example.
128
129 \code
130 // factorial.js
131 .pragma library
132
133 function factorial(a) {
134     a = parseInt(a);
135     if (a <= 0)
136         return 1;
137     else
138         return a * factorial(a - 1);
139 }
140 \endcode
141
142 The pragma declaration must appear before any JavaScript code excluding comments.
143
144 As they are shared, stateless library files cannot access QML component instance
145 objects or properties directly, although QML values can be passed as function
146 parameters.
147
148
149 \section2 Importing One JavaScript File From Another
150
151 If a JavaScript file needs to use functions defined inside another JavaScript file,
152 the other file can be imported using the \l {QML:Qt::include()}{Qt.include()}
153 function. This imports all functions from the other file into the current file's
154 namespace.
155
156 For example, the QML code below left calls \c showCalculations() in \c script.js,
157 which in turn can call \c factorial() in \c factorial.js, as it has included
158 \c factorial.js using \l {QML:Qt::include()}{Qt.include()}.
159
160 \table
161 \row
162 \o {1,2} \snippet doc/src/snippets/declarative/integrating-javascript/includejs/app.qml 0
163 \o \snippet doc/src/snippets/declarative/integrating-javascript/includejs/script.js 0
164 \row
165 \o \snippet doc/src/snippets/declarative/integrating-javascript/includejs/factorial.js 0
166 \endtable
167
168 Notice that calling \l {QML:Qt::include()}{Qt.include()} imports all functions from
169 \c factorial.js into the \c MyScript namespace, which means the QML component can also
170 access \c factorial() directly as \c MyScript.factorial().
171
172 In QtQuick 2.0, support has been added to allow JavaScript files to import other
173 JavaScript files and also QML modules using a variation of the standard QML import
174 syntax (where all of the previously described rules and qualifications apply).
175
176 A JavaScript file may import another in the following fashion:
177 \code
178 .import "filename.js" as UniqueQualifier
179 \endcode
180 For example:
181 \code
182 .import "factorial.js" as MathFunctions
183 \endcode
184
185 A JavaScript file may import a QML module in the following fashion:
186 \code
187 .import Module.Name MajorVersion.MinorVersion as UniqueQualifier
188 \endcode
189 For example:
190 \code
191 .import Qt.test 1.0 as JsQtTest
192 \endcode
193 In particular, this may be useful in order to access functionality provided
194 via a module API; see qmlRegisterModuleApi() for more information.
195
196 Due to the ability of a JavaScript file to import another script or QML module in
197 this fashion in QtQuick 2.0, some extra semantics are defined:
198 \list
199 \o a script with imports will not inherit imports from the QML file which imported it (so accessing Component.error will fail, for example)
200 \o a script without imports will inherit imports from the QML file which imported it (so accessing Component.error will succeed, for example)
201 \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
202 \endlist
203
204 The first semantic is conceptually correct, given that a particular script
205 might be imported by any number of QML files.  The second semantic is retained
206 for the purposes of backwards-compatibility.  The third semantic remains
207 unchanged from the current semantics for shared scripts, but is clarified here
208 in respect to the newly possible case (where the script imports other scripts
209 or modules).
210
211 \section1 Running JavaScript at Startup
212
213 It is occasionally necessary to run some imperative code at application (or
214 component instance) startup.  While it is tempting to just include the startup
215 script as \e {global code} in an external script file, this can have severe limitations
216 as the QML environment may not have been fully established.  For example, some objects
217 might not have been created or some \l {Property Binding}s may not have been run.
218 \l {QML JavaScript Restrictions} covers the exact limitations of global script code.
219
220 The QML \l Component element provides an \e attached \c onCompleted property that
221 can be used to trigger the execution of script code at startup after the
222 QML environment has been completely established. For example:
223
224 \code
225 Rectangle {
226     function startupFunction() {
227         // ... startup code
228     }
229
230     Component.onCompleted: startupFunction();
231 }
232 \endcode
233
234 Any element in a QML file - including nested elements and nested QML component
235 instances - can use this attached property.  If there is more than one \c onCompleted()
236 handler to execute at startup, they are run sequentially in an undefined order.
237
238 Likewise, the \l {Component::onDestruction} attached property is triggered on
239 component destruction.
240
241
242 \section1 JavaScript and Property Binding
243
244 Property bindings can be created in JavaScript by assigning the property with a \c function
245 that returns the required value.
246
247 See \l {qml-javascript-assignment}{Property Assignment versus Property Binding} for details.
248
249
250 \section1 Receiving QML Signals in JavaScript
251
252 To receive a QML signal, use the signal's \c connect() method to connect it to a JavaScript
253 function.
254
255 For example, the following code connects the MouseArea \c clicked signal to the \c jsFunction()
256 in \c script.js:
257
258 \table
259 \row
260 \o \snippet doc/src/snippets/declarative/integrating-javascript/connectjs.qml 0
261 \o \snippet doc/src/snippets/declarative/integrating-javascript/script.js 0
262 \endtable
263
264 The \c jsFunction() will now be called whenever MouseArea's \c clicked signal is emitted.
265
266 See \l{QML Signal and Handler Event System#Connecting Signals to Methods and Signals}
267 {Connecting Signals to Methods and Signals} for more information.
268
269
270 \section1 QML JavaScript Restrictions
271
272 QML executes standard JavaScript code, with the following restrictions:
273
274 \list
275 \o JavaScript code cannot modify the global object.
276
277 In QML, the global object is constant - existing properties cannot be modified or
278 deleted, and no new properties may be created.
279
280 Most JavaScript programs do not intentionally modify the global object.  However,
281 JavaScript's automatic creation of undeclared variables is an implicit modification
282 of the global object, and is prohibited in QML.
283
284 Assuming that the \c a variable does not exist in the scope chain, the following code
285 is illegal in QML.
286
287 \code
288 // Illegal modification of undeclared variable
289 a = 1;
290 for (var ii = 1; ii < 10; ++ii)
291     a = a * ii;
292 console.log("Result: " + a);
293 \endcode
294
295 It can be trivially modified to this legal code.
296
297 \code
298 var a = 1;
299 for (var ii = 1; ii < 10; ++ii)
300     a = a * ii;
301 console.log("Result: " + a);
302 \endcode
303
304 Any attempt to modify the global object - either implicitly or explicitly - will
305 cause an exception.  If uncaught, this will result in an warning being printed,
306 that includes the file and line number of the offending code.
307
308 \o Global code is run in a reduced scope
309
310 During startup, if a QML file includes an external JavaScript file with "global"
311 code, it is executed in a scope that contains only the external file itself and
312 the global object.  That is, it will not have access to the QML objects and
313 properties it \l {QML Scope}{normally would}.
314
315 Global code that only accesses script local variable is permitted.  This is an
316 example of valid global code.
317
318 \code
319 var colors = [ "red", "blue", "green", "orange", "purple" ];
320 \endcode
321
322 Global code that accesses QML objects will not run correctly.
323
324 \code
325 // Invalid global code - the "rootObject" variable is undefined
326 var initialPosition = { rootObject.x, rootObject.y }
327 \endcode
328
329 This restriction exists as the QML environment is not yet fully established.
330 To run code after the environment setup has completed, refer to
331 \l {Running JavaScript at Startup}.
332
333 \o The value of \c this is currently undefined in QML in the majority of contexts
334
335 The \c this keyword is supported when binding properties from JavaScript. 
336 In all other situations, the value of
337 \c this is undefined in QML.
338
339 To refer to any element, provide an \c id.  For example:
340
341 \qml
342 Item {
343     width: 200; height: 100
344     function mouseAreaClicked(area) {
345         console.log("Clicked in area at: " + area.x + ", " + area.y);
346     }
347     // This will not work because this is undefined
348     MouseArea {
349         height: 50; width: 200
350         onClicked: mouseAreaClicked(this)
351     }
352     // This will pass area2 to the function
353     MouseArea {
354         id: area2
355         y: 50; height: 50; width: 200
356         onClicked: mouseAreaClicked(area2)
357     }
358 }
359 \endqml
360
361 \endlist
362
363 \section1 Scarce Resources in JavaScript
364
365 As described in the documentation for \l{QML Basic Types}, a \c variant type
366 property may hold a "scarce resource" (image or pixmap).  There are several
367 important semantics of scarce resources which should be noted:
368
369 \list
370 \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
371 \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
372 \o A client may explicitly destroy a scarce resource, which will immediately release the resource
373 \endlist
374
375 In most cases, allowing the engine to automatically release the resource is
376 the correct choice.  In some cases, however, this may result in an invalid
377 variant being returned from a function in JavaScript, and in those cases it
378 may be necessary for clients to manually preserve or destroy resources for
379 themselves.
380
381 For the following examples, imagine that we have defined the following class:
382 \code
383 class AvatarExample : public QObject
384 {
385     Q_OBJECT
386     Q_PROPERTY(QPixmap avatar READ avatar WRITE setAvatar NOTIFY avatarChanged)
387 public:
388     AvatarExample(QObject *parent = 0) : QObject(parent), m_value(100, 100) { m_value.fill(Qt::blue); }
389     ~AvatarExample() {}
390
391     QPixmap avatar() const { return m_value; }
392     void setAvatar(QPixmap v) { m_value = v; emit avatarChanged(); }
393
394 signals:
395     void avatarChanged();
396
397 private:
398     QPixmap m_value;
399 };
400 \endcode
401
402 and that we have registered it with the QML type-system as follows:
403 \code
404 qmlRegisterType<AvatarExample>("Qt.example", 1, 0, "AvatarExample");
405 \endcode
406
407 The AvatarExample class has a property which is a pixmap.  When the property
408 is accessed in JavaScript scope, a copy of the resource will be created and
409 stored in a JavaScript object which can then be used within JavaScript.  This
410 copy will take up valuable system resources, and so by default the scarce
411 resource copy in the JavaScript object will be released automatically by the
412 declarative engine once evaluation of the JavaScript expression is complete,
413 unless the client explicitly preserves it.
414
415 \section2 Example One: Automatic Release
416
417 In this example, the resource will be automatically
418 released after the binding expression evaluation is
419 complete.
420
421 \qml
422 // exampleOne.qml
423 import QtQuick 1.0
424 import Qt.example 1.0
425
426 QtObject {
427     property AvatarExample a;
428     a: AvatarExample { id: example }
429     property variant avatar: example.avatar
430 }
431 \endqml
432
433 \code
434 QDeclarativeComponent component(&engine, "exampleOne.qml");
435 QObject *object = component.create();
436 // The scarce resource will have been released automatically
437 // after the binding expression was evaluated.
438 // Since the scarce resource was not released explicitly prior
439 // to the binding expression being evaluated, we get the
440 // expected result:
441 //object->property("scarceResourceCopy").isValid() == true
442 delete object;
443 \endcode
444
445 \section2 Example Two: Explicit Preservation
446
447 In this example, the resource must be explicitly preserved in order
448 to prevent the declarative engine from automatically releasing the
449 resource after evaluation of the imported script.
450
451 \code
452 // exampleTwo.js
453 .import Qt.example 1.0 as QtExample
454
455 var component = Qt.createComponent("exampleOne.qml");
456 var exampleOneElement = component.createObject(null);
457 var avatarExample = exampleOneElement.a;
458 var retn = avatarExample.avatar;
459
460 // without the following call, the scarce resource held
461 // by retn would be automatically released by the engine
462 // after the import statement in exampleTwo.qml, prior
463 // to the variable assignment.
464 retn.preserve();
465
466 function importAvatar() {
467     return retn;
468 }
469 \endcode
470
471 \qml
472 // exampleTwo.qml
473 import QtQuick 1.0
474 import Qt.example 1.0
475 import "exampleTwo.js" as ExampleTwoJs
476
477 QtObject {
478     property variant avatar: ExampleTwoJs.importAvatar()
479 }
480 \endqml
481
482 \code
483 QDeclarativeComponent component(&engine, "exampleTwo.qml");
484 QObject *object = component.create();
485 // The resource was preserved explicitly during evaluation of the
486 // JavaScript expression.  Thus, during property assignment, the
487 // scarce resource was still valid, and so we get the expected result:
488 //object->property("avatar").isValid() == true
489 // The scarce resource may not have been cleaned up by the JS GC yet;
490 // it will continue to consume system resources until the JS GC runs.
491 delete object;
492 \endcode
493
494 \section2 Example Three: Explicit Destruction
495
496 In the following example, we release (via destroy()) an explicitly preserved
497 scarce resource variant.  This example shows how a client may free system
498 resources by releasing the scarce resource held in a JavaScript object, if
499 required, during evaluation of a JavaScript expression.
500
501 \code
502 // exampleThree.js
503 .import Qt.example 1.0 as QtExample
504
505 var component = Qt.createComponent("exampleOne.qml");
506 var exampleOneElement = component.createObject(null);
507 var avatarExample = exampleOneElement.a;
508 var retn = avatarExample.avatar;
509 retn.preserve();
510
511 function importAvatar() {
512     return retn;
513 }
514
515 function releaseAvatar() {
516     retn.destroy();
517 }
518 \endcode
519
520 \qml
521 // exampleThree.qml
522 import QtQuick 1.0
523 import Qt.example 1.0
524 import "exampleThree.js" as ExampleThreeJs
525
526 QtObject {
527     property variant avatarOne
528     property variant avatarTwo
529
530     Component.onCompleted: {
531         avatarOne = ExampleThreeJs.importAvatar(); // valid at this stage
532         ExampleThreeJs.releaseAvatar();            // explicit release
533         avatarTwo = ExampleThreeJs.importAvatar(); // invalid at this stage
534     }
535 }
536 \endqml
537
538 \code
539 QDeclarativeComponent component(&engine, "exampleThree.qml");
540 QObject *object = component.create();
541 // The scarce resource was explicitly preserved by the client during
542 // the evaluation of the imported script, and so the scarce resource
543 // remains valid until the explicit call to releaseAvatar().  As such,
544 // we get the expected results:
545 //object->property("avatarOne").isValid() == true
546 //object->property("avatarTwo").isValid() == false
547 // Because the scarce resource was released explicitly, it will no longer
548 // be consuming any system resources (beyond what a normal JS Object would;
549 // that small overhead will exist until the JS GC runs, as per any other
550 // JavaScript object).
551 delete object;
552 \endcode
553
554 */