42cedfb84d3673ba1b893600ffd1f801ffe77b3a
[profile/ivi/qtdeclarative.git] / doc / src / declarative / javascriptblocks.qdoc
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: http://www.qt-project.org/
6 **
7 ** This file is part of the documentation of the Qt Toolkit.
8 **
9 ** $QT_BEGIN_LICENSE:FDL$
10 ** GNU Free Documentation License
11 ** Alternatively, this file may be used under the terms of the GNU Free
12 ** Documentation License version 1.3 as published by the Free Software
13 ** Foundation and appearing in the file included in the packaging of
14 ** this file.
15 **
16 ** Other Usage
17 ** Alternatively, this file may be used in accordance with the terms
18 ** and conditions contained in a signed written agreement between you
19 ** and Nokia.
20 **
21 **
22 **
23 **
24 ** $QT_END_LICENSE$
25 **
26 ****************************************************************************/
27
28 /*!
29 \page qdeclarativejavascript.html
30 \inqmlmodule QtQuick 2
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 \i {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 \i 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 var 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
383 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/avatarExample.h 0
384
385 and that we have registered it with the QML type-system as follows:
386
387 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/avatarExample.cpp 0
388
389 The AvatarExample class has a property which is a pixmap.  When the property
390 is accessed in JavaScript scope, a copy of the resource will be created and
391 stored in a JavaScript object which can then be used within JavaScript.  This
392 copy will take up valuable system resources, and so by default the scarce
393 resource copy in the JavaScript object will be released automatically by the
394 declarative engine once evaluation of the JavaScript expression is complete,
395 unless the client explicitly preserves it.
396
397 \section2 Example One: Automatic Release
398
399 In the following example, the scarce resource will be automatically released
400 after the binding evaluation is complete.
401
402 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/exampleOne.qml 0
403
404 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/avatarExample.cpp 1
405
406 \section2 Example Two: Automatic Release Prevented By Reference
407
408 In this example, the resource will not be automatically
409 released after the binding expression evaluation is
410 complete, because there is a property var referencing the
411 scarce resource.
412
413 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/exampleTwo.qml 0
414
415 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/avatarExample.cpp 2
416
417 \section2 Example Three: Explicit Preservation
418
419 In this example, the resource must be explicitly preserved in order
420 to prevent the declarative engine from automatically releasing the
421 resource after evaluation of the imported script.
422
423 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/exampleThree.js 0
424
425 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/exampleThree.qml 0
426
427 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/avatarExample.cpp 3
428
429 \section2 Example Four: Explicit Destruction
430
431 In the following example, we release (via destroy()) an explicitly preserved
432 scarce resource variant.  This example shows how a client may free system
433 resources by releasing the scarce resource held in a JavaScript object, if
434 required, during evaluation of a JavaScript expression.
435
436 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/exampleFour.js 0
437
438 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/exampleFour.qml 0
439
440 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/avatarExample.cpp 4
441
442 \section2 Example Five: Explicit Destruction And JavaScript References
443
444 One thing to be aware of when using "var" type properties is that they
445 hold references to JavaScript objects.  As such, if multiple references
446 to one scarce resource is held, and the client calls destroy() on one
447 of those references (to explicitly release the scarce resource), all of
448 the references will be affected.
449
450 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/exampleFive.qml 0
451
452 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/avatarExample.cpp 5
453
454 */