Reputation: 21
I try to use the Class and Namespace from the Firefox Add-on Sdk.
My problem is that I cannot access the data defined in the namespace from a listener function defined out of the class.
I've read different things and make some tests using this as example https://github.com/mozilla/addon-sdk/blob/master/lib/sdk/tabs/tab-fennec.js but I still don't know how to solve my problem.
So the class is initialized with a specific argument, this argument is saved in the namespace. Then I register an event listener and the listener needs to access the argument in the namespace. It doesn't work surely because of the "this" object. I've tried to use "bind" but it doesn't change anything.
Here's the simple code:
"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);
}
}
used in the main.js
const preferences = require("preferences")
var pref;
exports.main = function(options, callback) {
pref = preferences.Preferences("hello");
};
exports.onUnload = function(reason) {
pref.unload();
};
Thanks in advance
Upvotes: 1
Views: 165
Reputation: 21
Ok I've found a solution.
I need to bind the listener:
this.onPrefChange.bind(this);
As bind() create a new object, I keep the reference of the bound listener:
this.boundOnPrefChange = this.onPrefChange.bind(this);
So I can remove the listener using the bound reference:
prefSettings.removeListener("", this.boundOnPrefChange);
So now my code looks like 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;
//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;
If there are other ways to do it, please let me know.
Thanks
Upvotes: 1