JustWe
JustWe

Reputation: 4484

How to store a function and call it later in QML JavaScript

Here is part of code:

Repeater{
    model: [["Text A", function(){console.log("hello A")}],
            ["Text B", function(){console.log("hello B")}],
            ["Text C", function(){console.log("hello C")}],
            ["Text D", function(){console.log("hello D")}]]
    delegate: Button{
        text: modelData[0]
        onClicked: modelData[1](); // Type Error
    }
}

I want give different behavior for each button. I think it's supposed to be same as native JavaScript.

var func = function(){
  //...
}
func();

How to do this in QML JavaScript?

BTW, now my solution is:

Repeater{
    model: ["Text A",
            "Text B",
            "Text C",
            "Text D"]
    delegate: Button{
        text: modelData
        onClicked: {
           switch(index)
           {
              cast 0:
                console.log("hello A")
                break;
              cast 1:
                console.log("hello B")
                break;
              cast 2:
                console.log("hello C")
                break;
              cast 3:
                console.log("hello D")
                break;
           }
        }
    }
}

Upvotes: 3

Views: 1930

Answers (1)

dtech
dtech

Reputation: 49319

This looks like a bug to me, it just won't get to the function through the model interface. Or maybe a design limitation. As far as the function is concerned, it is undefined.

You could work around it like this:

  property var mod :
   [["Text A", function(){console.log("hello A")}],
    ["Text B", function(){console.log("hello B")}],
    ["Text C", function(){console.log("hello C")}],
    ["Text D", function(){console.log("hello D")}]]

  Column {
    Repeater {
      id: rep
      model: mod
      delegate: Button {
        text: modelData[0]
        onClicked: mod[index][1]()
      }
    }
  }

Upvotes: 2

Related Questions