I have QML code, for example this code
Item {
id:self;
function update(){
var visitFunc = self.applyUpdate;
innerTraversal(self,visitFunc);
}
function reset(){
var visitFunc = self.applyReset;
innerTraversal(self,visitFunc);
}
function innerTraversal(obj, visitFun){
console.log(typeof visitFun);
if(obj!== self && visitFun && typeof visitFun ==="function")
visitFun(obj);
if(hasChilderns(obj)){
var objChilderns = obj.children;
for(var i=0 ; i< objChilderns.length ; i++){
innerTraversal(objChilderns[i]);
}
}
}
function hasChilderns(obj){
if(typeof obj.children !== 'undefined')
return true;
else
return false;
}
function applyReset(obj){
if(typeof obj.reset === 'function')
obj.reset();
}
function applyUpdate(obj){
if(typeof obj.update === 'function')
obj.update();
}
}
in normal javascript this works cool, but when I use this code in QML the bad thing is visitFun always has type of undefined, and it does not work..
any idea how to make this work ?
Functions are first-class citizens in the functional programming paradigm, which means they are just like variables. They can be passed as arguments to other functions, assigned to variables, and returned by other functions.
Passing a function as an argument to the function is quite similar to the passing variable as an argument to the function. so variables can be returned from a function. The below examples describe passing a function as a parameter to another function.
QML has a deep JavaScript integration, and allows signal handlers and methods to be defined in JavaScript. Another core feature of QML is the ability to specify and enforce relationships between object properties using property bindings, which are also defined using JavaScript.
Arguments are Passed by Value The parameters, in a function call, are the function's arguments. JavaScript arguments are passed by value: The function only gets to know the values, not the argument's locations. If a function changes an argument's value, it does not change the parameter's original value.
In QtQuick 2 you should be able to bind functions to properties using
Item { //<-- declaration
id : item
property variant fun
}
item.fun : Qt.binding(function(){doSomething()}) //<--defintion
item.fun // <-- invocation without braces
So you could pass an object with a generic function as parameter.
In general, function overloading a can also be used to create a generic function for example to create a Button type:
---Button.qml
Item {
function fun() {} //<-- declaration (empty dummy)
MouseArea {
anchors.fill: parent
onClicked: {
fun(); //<-- invocation
}
}
}
---
---main.qml---
Button {
id: button
function fun() { //<-- defintion by overloading
doSomething
}
}
---
Clicking the button will activate its onClick handler and actually do something ;). Again, you would then pass the object with the generic function not the function itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With