Compare Revisions

Preferences

Change Revisions

Revision 44012:

Revision 44012 by Db48x on

Revision 44013:

Revision 44013 by Db48x on

Title:
Preferences
Preferences
Slug:
Code_snippets/Preferences
Code_snippets/Preferences
Tags:
Extensions, Add-ons, "Code snippets"
Extensions, Add-ons, "Code snippets"
Content:

Revision 44012
Revision 44013
tt322      Here's the code I like to use, as it makes for much better 
 >code reuse both within a project (because you can easily create m
 >ultiple listeners without duplicating the code) and across projec
 >ts (I put it in a common include file.) It's pretty similar to th
 >e previous example.
323    </p>
324    <pre>
325function prefListener(branchName, func)
326{
327    var prefService = Components.classes["@mozilla.org/preference
 >s-service;1"]
328                                .getService(Components.interfaces
 >.nsIPrefService);
329    var branch = prefService.getBranch(branchName);
330    branch.QueryInterface(Components.interfaces.nsIPrefBranch2);
331 
332    this.register = function()
333    {
334        branch.addObserver("", this, false);
335        branch.getChildList("", { })
336              .forEach(function (name) { func(branch, name); });
337    };
338 
339    this.unregister = function unregister()
340    {
341        if (branch)
342            branch.removeObserver("", this);
343    };
344 
345    this.observe = function(subject, topic, data)
346    {
347        if (topic == "nsPref:changed")
348            func(branch, data);
349    };
350}
351 
352var myListener = new prefListener("extensions.myextension",
353                                  function(branch, name)
354                                  {
355                                      switch (name) 
356                                      {
357                                          case "pref1":
358                                              // extensions.myext
 >ension.pref1 was changed
359                                              break;
360                                          case "pref2":
361                                              // extensions.myext
 >ension.pref2 was changed
362                                              break;
363                                      }
364                                  });
365myListener.register();
366</pre>
367    <p>

Back to History