Quote from Defining JavaScript Resources In QML:
Some JavaScript files act more like libraries - they provide a set of helper functions that take input and compute output, but never manipulate QML component instances directly.
What if I want a JS file that both:
- manipulates QML component instances (that are passed to it as arguments)
- doesn't get a copy of its code and data stored for every QML component instance that imports it?
I could get the "no data stored on every instance" part by, well, not putting global variables in the JS file. But, for some strange reason, a copy of the "code" part seems to be stored for every instance as well. I don't get why this is but I want to know whether I can circumvent it, and at what cost.
I think that the line you quoted from the documentation is incorrect, or at least very poorly worded; you can still have a JS file with .pragma library
in it and manipulate QML objects that are passed in as arguments to its functions. The sentence was probably referring to the previous section.
To share data across qml files, consider using a qml Singleton.
For data sharing purpose, I would not suggest using .pragma library
(@Mitch) for following reasons.
.pragma library
js provides limited functionality in qml object manipulation. While simple qml object manipulation (like property reading/writing) could be done with a .pragma library
js, it does NOT allow creating/deleting qml objects (as you can in regular non-library js). It will suck when your application becomes dynamic.
.pragma library
creating only one instance is merely an optimization in Qt implementation. It's never guaranteed that Qt creates exactly one instance, nor that your data would actually be shared.
Well, .pragma library
is not designed to do data sharing work from the very beginning. Just, don't try to do it this way.