1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: http://www.qt-project.org/
7 ** This file is part of the documentation of the Qt Toolkit.
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
17 ** Alternatively, this file may be used in accordance with the terms
18 ** and conditions contained in a signed written agreement between you
26 ****************************************************************************/
29 \page qdeclarativejavascript.html
30 \inqmlmodule QtQuick 2
31 \title Integrating JavaScript
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.
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
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.
47 \section1 Inline JavaScript
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
55 function factorial(a) {
60 return a * factorial(a - 1);
65 onClicked: console.log(factorial(10))
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
75 \section1 Separate JavaScript files
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.
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:
85 import "factorial.js" as MathFunctions
89 onClicked: console.log(MathFunctions.factorial(10))
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.
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).
107 \section2 Code-Behind Implementation Files
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
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
119 \section2 Stateless JavaScript libraries
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.
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.
133 function factorial(a) {
138 return a * factorial(a - 1);
142 The pragma declaration must appear before any JavaScript code excluding comments.
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
149 \section2 Importing One JavaScript File From Another
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
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()}.
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
165 \o \snippet doc/src/snippets/declarative/integrating-javascript/includejs/factorial.js 0
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().
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).
176 A JavaScript file may import another in the following fashion:
178 .import "filename.js" as UniqueQualifier
182 .import "factorial.js" as MathFunctions
185 A JavaScript file may import a QML module in the following fashion:
187 .import Module.Name MajorVersion.MinorVersion as UniqueQualifier
191 .import Qt.test 1.0 as JsQtTest
193 In particular, this may be useful in order to access functionality provided
194 via a module API; see qmlRegisterModuleApi() for more information.
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:
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
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
211 \section1 Running JavaScript at Startup
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.
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:
226 function startupFunction() {
230 Component.onCompleted: startupFunction();
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.
238 Likewise, the \l {Component::onDestruction} attached property is triggered on
239 component destruction.
242 \section1 JavaScript and Property Binding
244 Property bindings can be created in JavaScript by assigning the property with a \c function
245 that returns the required value.
247 See \l {qml-javascript-assignment}{Property Assignment versus Property Binding} for details.
250 \section1 Receiving QML Signals in JavaScript
252 To receive a QML signal, use the signal's \c connect() method to connect it to a JavaScript
255 For example, the following code connects the MouseArea \c clicked signal to the \c jsFunction()
260 \o \snippet doc/src/snippets/declarative/integrating-javascript/connectjs.qml 0
261 \o \snippet doc/src/snippets/declarative/integrating-javascript/script.js 0
264 The \c jsFunction() will now be called whenever MouseArea's \c clicked signal is emitted.
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.
270 \section1 QML JavaScript Restrictions
272 QML executes standard JavaScript code, with the following restrictions:
275 \o JavaScript code cannot modify the global object.
277 In QML, the global object is constant - existing properties cannot be modified or
278 deleted, and no new properties may be created.
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.
284 Assuming that the \c a variable does not exist in the scope chain, the following code
288 // Illegal modification of undeclared variable
290 for (var ii = 1; ii < 10; ++ii)
292 console.log("Result: " + a);
295 It can be trivially modified to this legal code.
299 for (var ii = 1; ii < 10; ++ii)
301 console.log("Result: " + a);
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.
308 \o Global code is run in a reduced scope
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}.
315 Global code that only accesses script local variable is permitted. This is an
316 example of valid global code.
319 var colors = [ "red", "blue", "green", "orange", "purple" ];
322 Global code that accesses QML objects will not run correctly.
325 // Invalid global code - the "rootObject" variable is undefined
326 var initialPosition = { rootObject.x, rootObject.y }
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}.
333 \o The value of \c this is currently undefined in QML in the majority of contexts
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.
339 To refer to any element, provide an \c id. For example:
343 width: 200; height: 100
344 function mouseAreaClicked(area) {
345 console.log("Clicked in area at: " + area.x + ", " + area.y);
347 // This will not work because this is undefined
349 height: 50; width: 200
350 onClicked: mouseAreaClicked(this)
352 // This will pass area2 to the function
355 y: 50; height: 50; width: 200
356 onClicked: mouseAreaClicked(area2)
363 \section1 Scarce Resources in JavaScript
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:
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
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
381 For the following examples, imagine that we have defined the following class:
383 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/avatarExample.h 0
385 and that we have registered it with the QML type-system as follows:
387 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/avatarExample.cpp 0
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.
397 \section2 Example One: Automatic Release
399 In the following example, the scarce resource will be automatically released
400 after the binding evaluation is complete.
402 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/exampleOne.qml 0
404 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/avatarExample.cpp 1
406 \section2 Example Two: Automatic Release Prevented By Reference
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
413 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/exampleTwo.qml 0
415 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/avatarExample.cpp 2
417 \section2 Example Three: Explicit Preservation
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.
423 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/exampleThree.js 0
425 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/exampleThree.qml 0
427 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/avatarExample.cpp 3
429 \section2 Example Four: Explicit Destruction
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.
436 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/exampleFour.js 0
438 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/exampleFour.qml 0
440 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/avatarExample.cpp 4
442 \section2 Example Five: Explicit Destruction And JavaScript References
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.
450 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/exampleFive.qml 0
452 \snippet doc/src/snippets/declarative/integrating-javascript/scarceresources/avatarExample.cpp 5