2017-04-03 66 views
2

下面是部分代碼:以後怎麼存儲功能,並調用它在QML的JavaScript

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 
    } 
} 

我想給每個按鈕不同的行爲。我認爲它應該與原生JavaScript相同。

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

如何在QML JavaScript中做到這一點?

順便說一句,我現在的解決方案是:

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; 
      } 
     } 
    } 
} 
+0

你能更好地解釋我嗎? – eyllanesc

+0

@eyllanesc我想在組件(按鈕)創建時將lambda函數的函數指針作爲變量存儲到數組(模型)中。然後在單擊按鈕時調用存儲的函數指針。 – Jiu

回答

1

這看起來像我的一個錯誤,它只是不會通過模型接口獲取到的功能。或者可能是設計限制。就功能而言,它是undefined

你可以解決它是這樣的:

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]() 
     } 
    } 
    } 
+0

謝謝,它效果很好。 – Jiu

相關問題