Qt-based Javascript Published May 17, 2013 | By Xingtao
Zhang
Original article: Jörg bornemann-qtified
Javascript
Writing JavascriptCodeIn a short time, I will miss some functions available in the QT C ++ API. A simple example is:Qlist: Contains. In JavaScript, check whether an array contains a definite element like this:
VaR names = ["Egon", "Peter", "Raymond", "Waldo"]; If (names. indexof ("Waldo ")! =-1) print ("we 've found him! ");
If we can useCantainsMethod. HoweverArrayNot provided.
Fortunately, JavaScript allows us to add methods by modifying the corresponding prototype object to the built-in type (inbuilt types.
Array. Prototype. Contains = function (e) {return this. indexof (e )! =-1;} If (names. Contains ("Waldo") print ("we 've found him! ");
Yeah! Now we can use all ArraysContainMethod.
However, when you try to iterate the keyword of an array, there is a potential surprise.
For (var I in names) print (I );
Will print:
0123 contains
I know that array iteration can be completed through index variables ...... But ...... Additional keywords are unpredictable and troublesome.
To solve this problemContainsThe property is marked as non-enumerable. We can use the object. defineproperty function, which is from Javascript
Available after 1.8.5.
Object. defineproperty (array. prototype, "contains", {value: function (e) {return this. indexof (e )! =-1;}, enumerable: false // This is the default and can be omitted .})
We giveObject. definepropertyPass the object we want to enhance, the name of the attribute to be added, and a flag description object containing our new attribute.
ContainsThe value is the function that we explicitly pass to the prototype. When usingFor (... In ...)When loopingEnumerableSetting property to false will hideContains.
In this way, we can set the built-in JavaScript type.ArrayAndStringCreate APIs that are as friendly as QT. This can be placed in a. js file and used in the qml/JS or qbs project file.
What do you think? Is such an API helpful for your qml code? Which qlist or qstring method do you want most?