“Some JS files act more like libraries - they […] never manipulate QML component instances directly” - middle ground?

…衆ロ難τιáo~ 提交于 2019-12-13 07:05:01

问题


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.


回答1:


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.




回答2:


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.

  1. .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.

  2. .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.

  3. Well, .pragma library is not designed to do data sharing work from the very beginning. Just, don't try to do it this way.



来源:https://stackoverflow.com/questions/39497187/some-js-files-act-more-like-libraries-they-never-manipulate-qml-compone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!