使用Firefox插件Sdk中的类和命名空间

Use Class and Namespace from the Firefox Add-on Sdk

本文关键字:命名空间 Firefox 插件 Sdk 使用      更新时间:2023-09-26

我尝试使用Firefox Add-on-Sdk中的class和Namespace。

我的问题是,我无法从类外定义的侦听器函数访问命名空间中定义的数据。

我读过不同的东西,并以此为例进行了一些测试https://github.com/mozilla/addon-sdk/blob/master/lib/sdk/tabs/tab-fennec.js但我仍然不知道如何解决我的问题。

因此,类是用一个特定的参数初始化的,这个参数保存在命名空间中。然后我注册了一个事件侦听器,侦听器需要访问命名空间中的参数。因为"这个"对象,它肯定不起作用。我试过使用"绑定",但它不会改变任何东西。

这是一个简单的代码:

"use strict"
const { Class } = require("sdk/core/heritage");
const preferencesNS = require("sdk/core/namespace").ns();
const prefSettings = require("sdk/simple-prefs");
const Preferences = Class({
    initialize: function initialize(flag) {     
        preferencesNS(this).flag = flag;
        //Registers the pref event listener 
        prefSettings.on("", onPrefChange);      
    },
    unload: function unload() {     
        //Unregisters the pref event listener 
        prefSettings.removeListener("", onPrefChange);
    }
});
exports.Preferences = Preferences;
//The listener function
const onPrefChange = (prefName) => {        
    if ( preferencesNS(this).flag) {
        console.log(preferencesNS(this).flag);
        console.log(prefName);
    }
}

在main.js 中使用

const preferences = require("preferences")
var pref;
exports.main = function(options, callback) {
    pref = preferences.Preferences("hello");    
};
exports.onUnload = function(reason) {
    pref.unload();
};

提前感谢

好的,我找到了一个解决方案。

我需要绑定侦听器:

this.onPrefChange.bind(this);

当bind()创建一个新对象时,我保留了绑定侦听器的引用:

this.boundOnPrefChange = this.onPrefChange.bind(this);

因此,我可以使用绑定引用删除侦听器:

prefSettings.removeListener("", this.boundOnPrefChange);

现在我的代码是这样的:

"use strict"
const { Class } = require("sdk/core/heritage");
const preferencesNS = require("sdk/core/namespace").ns();
const prefSettings = require("sdk/simple-prefs");
const Preferences = Class({
    initialize: function initialize(flag) {     
        preferencesNS(this).flag = flag;
        //Bind the listener and keep the reference
        this.boundOnPrefChange = this.onPrefChange.bind(this);
        //Registers the bound pref event listener 
        prefSettings.on("", this.boundOnPrefChange);
    },
    unload: function unload() {     
        //Unregisters the bound pref event listener
        prefSettings.removeListener("", this.boundOnPrefChange);
    },
    onPrefChange: function (prefName) {      
        if ( preferencesNS(this).flag) {
            console.log(preferencesNS(this).flag);
            console.log(prefName);
        }
    }
});
exports.Preferences = Preferences;

如果还有其他方法,请告诉我。

感谢