Bind to imported Javascript property

2.2k Views Asked by At

How do I bind to a Javascript resource?

I'm new to QML and are probably thinking about this the wrong way, but in the below example, I'd like the button to say "World" when I press it.

main.qml

import QtQuick 2.0
import QtQuick.Controls 1.0
import "model.js" as Model


Button {
    id: button
    text: Model.text

    onClicked: {
        Model.text = "World";
        print("Model.text is:", Model.text)
        print("button.text is:", button.text)
        // Model.text is "World"
        // button.text is "Hello"
        // They should both be "World"
    }
}

model.js

var text = "Hello";

I also tried using a Qt.binding, but it didn't make a difference.

main.qml

import QtQuick 2.0
import QtQuick.Controls 1.0
import "model.js" as Model


Button {    
    onClicked: {
        Model.text = "World";
    }

    Component.onCompleted: {
        text = Qt.binding(function () { return Model.text })
    }
}

The end result I'm looking for is to have properties in a dedicated Javascript resource, such as window height, colors and image paths etc. and have whichever item is using them to stay in sync with any changes made to the resource.

Edit

Found a related question: declare global property in QML for other QML files

1

There are 1 best solutions below

2
On BEST ANSWER

Generally, you can't bind QML property to variable from pure JavaScript module. My advice is to use lightweight QML alternative - QtObject . You can add custom set of properties and signals to it, for example:

QtObject {
    id: mySettings
    property string iconPath: "./icon.png"
}

This properties can be binded later exactly as you want.