aboutsummaryrefslogtreecommitdiffstats
path: root/src/qml/jsruntime/qv4engine.cpp
diff options
context:
space:
mode:
authorAlex Shaw <alex.shaw.as@gmail.com>2021-04-25 17:57:37 -0400
committerAlex Shaw <alex.shaw.as@gmail.com>2021-05-01 17:26:00 -0400
commit3464655f5e2adaa1aed8925a9a54b8fb5f238f31 (patch)
treeebb7c46c7d4f1af6e4b1853a74d7502fee3c450f /src/qml/jsruntime/qv4engine.cpp
parent689522817dc559056f7c55f811a189c4821b7787 (diff)
Add QJSEngine::registerModule
Some applications that use JavaScript as a scripting language may want to extend JS through C++ code. The current way to do that is with global objects. ES6 provides a better way of encapsulating code: modules. registerModule() allows an application to provide a QJSValue as a named module. Developers familiar with Node.js will find this very easy to use. Example: ```c++ QJSValue num(666); myEngine.registerModule("themarkofthebeast", num); ``` ```js import badnews from "themarkofthebeast"; ``` [ChangeLog][QtQml][QJSEngine] Adds the ability to register QJSValues in C++ as modules for importing in MJS files. Change-Id: I0c98dcb746aa2aa15aa2ab3082129d106413a23b Reviewed-by: Ulf Hermann <ulf.hermann@qt.io>
Diffstat (limited to 'src/qml/jsruntime/qv4engine.cpp')
-rw-r--r--src/qml/jsruntime/qv4engine.cpp17
1 files changed, 17 insertions, 0 deletions
diff --git a/src/qml/jsruntime/qv4engine.cpp b/src/qml/jsruntime/qv4engine.cpp
index 69db5efd05..0c3f16651a 100644
--- a/src/qml/jsruntime/qv4engine.cpp
+++ b/src/qml/jsruntime/qv4engine.cpp
@@ -879,6 +879,10 @@ ExecutionEngine::ExecutionEngine(QJSEngine *jsEngine)
ExecutionEngine::~ExecutionEngine()
{
modules.clear();
+ for (auto val : nativeModules) {
+ PersistentValueStorage::free(val);
+ }
+ nativeModules.clear();
qDeleteAll(m_extensionData);
delete m_multiplyWrappedQObjects;
m_multiplyWrappedQObjects = nullptr;
@@ -2072,6 +2076,19 @@ QQmlRefPointer<ExecutableCompilationUnit> ExecutionEngine::loadModule(const QUrl
return newModule;
}
+void ExecutionEngine::registerModule(const QString &_name, const QJSValue &module)
+{
+ const QUrl url(_name);
+ QMutexLocker moduleGuard(&moduleMutex);
+ const auto existingModule = nativeModules.find(url);
+ if (existingModule != nativeModules.end())
+ return;
+
+ QV4::Value* val = this->memoryManager->m_persistentValues->allocate();
+ *val = QJSValuePrivate::asReturnedValue(&module);
+ nativeModules.insert(url, val);
+}
+
bool ExecutionEngine::diskCacheEnabled() const
{
return (!disableDiskCache() && !debugger()) || forceDiskCache();