Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries over the next few weeks. Thanks for all your past and future contributions.

Store JavaScript object references in QML objects

From Wiki
Jump to: navigation, search
Article Metadata
Platform(s): any
Created: vivainio (03 Jan 2011)
Last edited: hamishwillee (13 Jun 2012)

QML objects only allow storing elementary data with "property" statement, e.g.:

property int a : 22
property string foo : "bar"
property variant mylist: [1,2,3]

You may be easily cheated to assume that "property variant" can store arbitrary javascript objects, but this is not the case. As an example, if you acquire a javascript Object or Array from a function written in javascript, it will be severely mangled when assigned to mylist. This manifests as weird bugs in your application.

As a workaround, this article presents a priv() function that allows you to associate a single javascript "container" object with each QML object. This single container object will of course contain all your "private" javascript objects.

the "priv" function is implemented in a single .js file qmlprivate.js:

.pragma library
var _privs = {}
function priv(key) {
var h = key.toString()
var o = _privs[key]
if (!o) {
o = {}
_privs[key] = o
return o

In your qml application, you use it like this:

import "qmlprivate.js" as P
QtObject {
// property variant foo // THIS CAN'T CONTAIN JS REFERENCES, AVOID!!!
id: root
function setCallback(cb) {
// instead, JS references can be stored in the associated "priv" object:
P.priv(root).callback = cb
var bar = P.priv(root).callback

Note how you pass the QML object as an argument to priv(). The function here uses toString() result as "hash" value, as it contains the pointer address for QML object.

This page was last modified on 13 June 2012, at 10:58.
113 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.


Thank you!

We appreciate your feedback.