Search code examples
javascriptgobjectgnome-shell-extensionsgjs

What is the correct way in GJS to define a GObject property for an Array?


I see in the GJS GObject overrides there are definitions for most types that correspond to Javascript types, but how should I define a property for a standard Array of strings? Some options that have occurred to me:

  • use TYPE_OBJECT and a GList, but will GJS map this to an Array when I retrieve it?
  • use TYPE_OBJECT and a GVariant with an "as" type and unpack it myself
  • use TYPE_BOXED and TYPE_ARRAY, but is TYPE_ARRAY comparable to Javascript's Array type?

Solution

  • This is not currently possible. Subscribe to https://bugzilla.gnome.org/show_bug.cgi?id=727787 to be notified when there is progress on it.

    I have successfully used the second option (GVariant with type as) in the past. The GList option won't work, since GJS doesn't pay attention to the type of values stored in the GList. The third option I'm not sure about.

    Here's a minimal example showing how to use the GVariant option:

    const GObject = imports.gi.GObject;
    const GLib = imports.gi.GLib;
    
    const MyClass = GObject.registerClass({
        Properties: {
            'prop': GObject.param_spec_variant('prop', 'Prop', 'Prop',
                new GLib.VariantType('as'), null,
                GObject.ParamFlags.READABLE),
        },
    }, class MyClass extends GObject.Object {
        get prop() {
            return new GLib.Variant('as', ['one', 'two']);
        }
    });
    
    print(new MyClass().prop.deep_unpack());
    

    (If you're not using the new class syntax, it still works in a similar way with the old Lang.Class.)