gpt4 book ai didi

javascript - 为什么QML引擎会多次实例化同一个脚本?

转载 作者:行者123 更新时间:2023-11-29 10:06:24 25 4
gpt4 key购买 nike

假设我们有以下 JS 文件:

逻辑.js

function Car(){}

和这些 QML 文件:

comp1.qml

import 'qrc:/js/logic.js' as Logic

Item{
property var item: Logic
}

comp2.qml

import 'qrc:/js/logic.js' as Logic

Item{
property var item: Logic
}

如果您运行并评估,您会发现那些 item 属性不相等。为什么?

在我的应用程序中,在一个 QML 文件中,我new 一个对象并想检查它是否是 instanceof 构造函数,但由于这些构造函数不是'如果不相等(因为那些 Logic 不相等),instanceof 运算符总是返回 false

最佳答案

Code-Behind Implementation Resource文档解释了这种行为:

Most JavaScript files imported into a QML document are stateful implementations for the QML document importing them. In these cases, each instance of the QML object type defined in the document requires a separate copy of the JavaScript objects and state in order to behave correctly.

The default behavior when importing JavaScript files is to provide a unique, isolated copy for each QML component instance. If that JavaScript file does not import any resources or modules with a .import statement, its code will run in the same scope as the QML component instance and consequently can access and manipulate the objects and properties declared in that QML component. Otherwise, it will have its own unique scope, and objects and properties of the QML component should be passed to the functions of the JavaScript file as parameters if they are required.

解决方案是将 .pragma library 放在 JavaScript 文件的顶部。这将允许它被多个 QML 文件共享。

下一节,Shared JavaScript Resources (Libraries)对此进行了更详细的介绍。

关于javascript - 为什么QML引擎会多次实例化同一个脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42483999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com