我正在编写首选项 View GNOME shell 扩展和使用 imports.lang
时面临的问题以面向对象的方式编写应用程序的函数。
const Gtk = imports.gi.Gtk
const Lang = imports.lang
Gtk.init(null)
const MyWindow = new Lang.Class({...})
第一次打开首选项窗口有效,但随后会抛出以下错误:
Error: Type name Gjs_MyWindow is already registered
.第一次关闭窗口时,我收到此错误:TypeError: prefsModule.init is not a function
.以下更具命令性的代码有效:
const Gtk = imports.gi.Gtk
Gtk.init(null)
const window = new Gtk.Window({ type: Gtk.WindowType.TOPLEVEL })
根据抛出的错误,我的猜测是该类正在被重新定义。如何避免重新定义并接收定义的类? (有没有我可以引用的文档?)
最佳答案
看起来正确的答案在 this discussion .
If you extend a GObject class (anything from St, Clutter, Gtk, etc.), you're registering a new GType, and that's not possible for extensions.
...
Extensions are dynamic modules, and they can be loaded and unloaded - but that's not at all possible for GTypes.
所以,不要扩展 GTypes。相反,使用看起来像这样的“委托(delegate)模式”。
const Class = new Lang.Class({
Name: "Class",
_init: function() {
this.actor = new St.Button();
}
)};
话虽如此,如果您查看系统上安装的扩展并执行类似 grep -rn 'Extends: Gtk' /usr/share/gnome-shell/extensions/
的操作,您会看到一些扩展仍然扩展了 GTypes,并且不会导致任何错误。但是您会注意到 extension.js
中从未这样做过。文件...不要在这里询问更多细节,这就是我今天所知道的!
关于gnome - 如何检查 Gjs 类是否已经定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42702883/