我尝试使用 Firefox Add-on Sdk 中的类和命名空间。
我的问题是我无法从类外定义的监听器函数访问命名空间中定义的数据。
我已经阅读了不同的内容并以此为例进行了一些测试 https://github.com/mozilla/addon-sdk/blob/master/lib/sdk/tabs/tab-fennec.js但我还是不知道如何解决我的问题。
因此该类使用特定参数进行初始化,该参数保存在命名空间中。 然后我注册一个事件监听器,该监听器需要访问命名空间中的参数。 由于“this”对象,它不一定有效。 我尝试过使用“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();
};
提前致谢
最佳答案
好的,我找到了解决方案。
我需要绑定(bind)监听器:
this.onPrefChange.bind(this);
当bind()创建一个新对象时,我保留绑定(bind)监听器的引用:
this.boundOnPrefChange = this.onPrefChange.bind(this);
所以我可以使用绑定(bind)引用删除监听器:
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;
如果还有其他方法,请告诉我。
谢谢
关于javascript - 使用 Firefox Add-on Sdk 中的类和命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25662090/