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 1
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 \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.
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:
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 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:
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 class AvatarExample : public QObject
386 Q_PROPERTY(QPixmap avatar READ avatar WRITE setAvatar NOTIFY avatarChanged)
388 AvatarExample(QObject *parent = 0) : QObject(parent), m_value(100, 100) { m_value.fill(Qt::blue); }
391 QPixmap avatar() const { return m_value; }
392 void setAvatar(QPixmap v) { m_value = v; emit avatarChanged(); }
395 void avatarChanged();
402 and that we have registered it with the QML type-system as follows:
404 qmlRegisterType<AvatarExample>("Qt.example", 1, 0, "AvatarExample");
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.
415 \section2 Example One: Automatic Release
417 In this example, the resource will be automatically
418 released after the binding expression evaluation is
424 import Qt.example 1.0
427 property AvatarExample a;
428 a: AvatarExample { id: example }
429 property variant avatar: example.avatar
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
441 //object->property("scarceResourceCopy").isValid() == true
445 \section2 Example Two: Explicit Preservation
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.
453 .import Qt.example 1.0 as QtExample
455 var component = Qt.createComponent("exampleOne.qml");
456 var exampleOneElement = component.createObject(null);
457 var avatarExample = exampleOneElement.a;
458 var retn = avatarExample.avatar;
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.
466 function importAvatar() {
474 import Qt.example 1.0
475 import "exampleTwo.js" as ExampleTwoJs
478 property variant avatar: ExampleTwoJs.importAvatar()
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.
494 \section2 Example Three: Explicit Destruction
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.
503 .import Qt.example 1.0 as QtExample
505 var component = Qt.createComponent("exampleOne.qml");
506 var exampleOneElement = component.createObject(null);
507 var avatarExample = exampleOneElement.a;
508 var retn = avatarExample.avatar;
511 function importAvatar() {
515 function releaseAvatar() {
523 import Qt.example 1.0
524 import "exampleThree.js" as ExampleThreeJs
527 property variant avatarOne
528 property variant avatarTwo
530 Component.onCompleted: {
531 avatarOne = ExampleThreeJs.importAvatar(); // valid at this stage
532 ExampleThreeJs.releaseAvatar(); // explicit release
533 avatarTwo = ExampleThreeJs.importAvatar(); // invalid at this stage
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).