![](/img/trans.png)
[英]Is it possible to use Firefox Add-on SDK from a Greasemonkey script?
[英]Use Class and Namespace from the Firefox Add-on Sdk
我嘗試使用Firefox附加SDK中的類和命名空間。
我的問題是我無法從類之外定義的偵聽器函數訪問命名空間中定義的數據。
我讀過不同的東西,並以此為例進行了一些測試,例如https://github.com/mozilla/addon-sdk/blob/master/lib/sdk/tabs/tab-fennec.js,但我仍然不知道如何解決我的問題。
因此,使用特定的參數初始化該類,該參數保存在名稱空間中。 然后,我注冊一個事件偵聽器,該偵聽器需要訪問名稱空間中的參數。 由於存在“ this”對象,因此不能保證正常工作。 我嘗試使用“綁定”,但是它沒有任何改變。
這是簡單的代碼:
"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;
如果還有其他方法,請告訴我。
謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.