Petr Tripolsky
Petr Tripolsky

Reputation: 1613

Send callback as argument to QJSValue::callAsConstructor()

When trying to call a JavaScript function from C ++ using QJSEngine, all argument properties whose values store functions are mysteriously lost. Why it happens? Is there any way around this bug? If you try to pass a function without an object, the undefined value is also transmitted.

qjsengine-bug

QT += core qml quick quickcontrols2
TARGET = qjsengine-bug
TEMPLATE = app
DEFINES += QT_DEPRECATED_WARNINGS
CONFIG += c++11 console
SOURCES += main.cpp

main.cpp

#include <QCoreApplication>
#include <QJSValueIterator>
#include <QJSEngine>
#include <QJSValue>
#include <QtGlobal>

#include <iostream>

void myMessageOutput(
    QtMsgType t,
    const QMessageLogContext &c,
    const QString &msg
) {
    Q_UNUSED(t);
    Q_UNUSED(c);
    std::cout << msg.toStdString() << "\n";
}

int main(int argc, char *argv[]) {
    qInstallMessageHandler(myMessageOutput);
    QCoreApplication app(argc, argv);

    QJSEngine engine;
    engine.installExtensions(QJSEngine::ConsoleExtension);
    QJSValue constructor = engine.evaluate(
        "(function Component(props){console.log(JSON.stringify(props))})"
    );

    QJSValue callBack = engine.evaluate("(function(text){console.log(text)})");
    callBack.call({"There is no error. Valid JavaScript code..."});

    callBack.call({"Let's create an object, add a couple of props to it"});

    QJSValue object = engine.newObject();
    object.setProperty("First", 1);
    object.setProperty("Second", callBack);
    object.setProperty("Third", "#2");

    QJSValueIterator iter(object);
    while (iter.hasNext()) {
        iter.next();
        callBack.call({
            QString("name: %1, value: %2")
                .arg(iter.name())
                .arg(iter.value().toString())
        });
    }

    callBack.call({"Correct. Three fields"});
    callBack.call({"Let's try to pass an object to the constructor parameters"});

    constructor.callAsConstructor({object});

    callBack.call({"Where did the second property go?"});

    return app.exec();
}

enter image description here

Upvotes: 1

Views: 725

Answers (1)

Vivick
Vivick

Reputation: 4991

As defined, JSON doesn't have anything to represent functions, thus JSON.stringify a function as property will result in a "missing" property (or a function in an array, or a function).

Upvotes: 1

Related Questions