Thought I’d share some more Javascript snippets with you zany kids.
Firstly, how to implement an interface (specifically a GInterface), for example an Mx.ItemFactory:
const ButtonFactory = new Lang.Class({ Name: 'ButtonFactory', Extends: GObject.Object, Implements: [ Mx.ItemFactory ], _init : function (callback) { this.parent(); this._callback = callback; }, vfunc_create : function () { let button = new Button(); button.connect('clicked', Lang.bind(this, function () { this._callback(button); })); return button; }, }); |
The important thing to notice is the vfunc_ that gets prepended to any calls you’re overriding from the library. Also be aware of your terminating commas, semicolons and braces. ((Obviously the entire class system here is a hack, which is what makes it so reminiscent of Perl.))
Of course, we want to bind extra attributes into the classes built by our factory (I’m not sure why Mx.ItemFactorys don’t just pass a row so that we can do whatever we like in the factory). Anyway, classes are easy in Javascript so we can just extend Mx.Button to include a property we can bind:
const Button = new Lang.Class({ Name: 'Button', Extends: Mx.Button, Properties: { 'id': GObject.ParamSpec.string('id', '', '', GObject.ParamFlags.READABLE | GObject.ParamFlags.WRITABLE, ''), }, _init : function (params) { this.parent(params); this._id = ''; }, get id () { return this._id; }, set id (val) { this._id = val; }, }); |
Again be aware of missing commas.
For more examples take a look at testGObjectClass.js. You should also know that much of this requires a recent gjs, so it’ll be available in GNOME 3.4, but not 3.2.
If you’re interested, here’s the code that uses this factory:
let factory = new ButtonFactory(Lang.bind(this, function (button) { ... })); let view = new Mx.ListView({ 'model': model, 'factory': factory, }); view.add_attribute('label', 0); view.add_attribute('id', 1); |
Thanks to Jasper St. Pierre for the help.