我尝试使用Firefox Add-on Sdk中的Class和Namespace。
我的问题是我无法从类中定义的侦听器函数访问命名空间中定义的数据。
我已经阅读了不同的内容并使用此示例https://github.com/mozilla/addon-sdk/blob/master/lib/sdk/tabs/tab-fennec.js进行了一些测试,但我仍然不知道如何解决我的问题。
因此,使用特定参数初始化类,此参数保存在命名空间中。 然后我注册一个事件监听器,监听器需要访问命名空间中的参数。 由于"这个"它确实无法正常工作。宾语。 我试过用#34; bind"但它并没有改变任何东西。
这是简单的代码:
"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();
};
提前致谢
答案 0 :(得分:1)
好的,我找到了解决方案。
我需要绑定侦听器:
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;
如果还有其他方法,请告诉我。
由于