Global Object, Scope and javascript
-
wrote on 30 Oct 2010, 23:29 last edited by
main.qml
@
import Qt 4.7import "myscript.js" as MyScript
Rectangle {
id:mainMyScript.myFuction(); // This will execute fine, scope is fine SecondQML {
}
}
@myscript.js
@
function myFuction() {
print('inside my function');
}
@SecondQML.qml
@
Rectangle {MouseArea {
id: mouseArea
anchors.fill: parent
onClicked: {
MyScript.myFunction(); // Will not execute
}
}
}
@I also tried main.MyScript.myFunction() it is out of scope. I need to be able to reference the same script instance bound in main.qml and not a newly initiated script from inside secondQML.qml
I can access main from here because of hierarchy but I am not sure why I cannot get to the MyScript property.
-
wrote on 31 Oct 2010, 00:23 last edited by
try parent.MyScript.myFunction();
-
wrote on 31 Oct 2010, 00:31 last edited by
TypeError: Result of expression 'parent.MyScript' [undefined] is not an object.
-
wrote on 31 Oct 2010, 00:44 last edited by
try parent.parent.MyScript.myFunction(); because the first parent is the rectangle from SecondQML and the parent to that is main rectangle
-
wrote on 31 Oct 2010, 04:12 last edited by
I don't believe it to be a parenting issue, as I have tried was you have suggested and made sure it was the proper parent. I think it has to do with the way the property MyScript is declared as an import. It might need to be referenced in a different manner or maybe it is not possible what I wish to do.
-
wrote on 1 Nov 2010, 05:36 last edited by
Hi,
Imports are document specific (we should try to make this clearer in the docs!), which is why the above is not working. A couple things you could try:
- Add a "wrapper" in main.qml; this wrapper should be accessible to children
@function myFunction() {
MyScript.myFuction();
}@ - Use the "library pragma":http://doc.qt.nokia.com/4.7/qdeclarativejavascript.html#stateless-javascript-libraries to import a shared copy of the script to both files.
Regards,
Michael - Add a "wrapper" in main.qml; this wrapper should be accessible to children
-
wrote on 15 Nov 2010, 12:56 last edited by
Hi
If import is document specific, how can I use the same global variant in two different qml files, they don't have any relationship. -
wrote on 15 Nov 2010, 23:56 last edited by
[quote author="oseeker" date="1289825785"]If import is document specific, how can I use the same global variant in two different qml files, they don't have any relationship.[/quote]
In most cases there will be a shared "root" QML file (the root of the QML tree for your application), which is accessible throughout the application (if the root component has id "root", its properties will be available to all ancestors as root.propertyName).
For a shared variable in a JS file, the "library pragma" solution mentioned above should allow access to the same value from different QML files (both QML files will need to import the JS file).