addon-sdk/source/lib/sdk/event/chrome.js

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/addon-sdk/source/lib/sdk/event/chrome.js	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,54 @@
     1.4 +/* This Source Code Form is subject to the terms of the Mozilla Public
     1.5 + * License, v. 2.0. If a copy of the MPL was not distributed with this
     1.6 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
     1.7 +
     1.8 +"use strict";
     1.9 +
    1.10 +module.metadata = {
    1.11 +  "stability": "unstable"
    1.12 +};
    1.13 +
    1.14 +const { Cc, Ci, Cr } = require("chrome");
    1.15 +const { emit, on, off } = require("./core");
    1.16 +const { addObserver } = Cc['@mozilla.org/observer-service;1'].
    1.17 +                        getService(Ci.nsIObserverService);
    1.18 +
    1.19 +// Simple class that can be used to instantiate event channel that
    1.20 +// implements `nsIObserver` interface. It's will is used by `observe`
    1.21 +// function as observer + event target. It basically proxies observer
    1.22 +// notifications as to it's registered listeners.
    1.23 +function ObserverChannel() {}
    1.24 +Object.freeze(Object.defineProperties(ObserverChannel.prototype, {
    1.25 +  QueryInterface: {
    1.26 +    value: function(iid) {
    1.27 +      if (!iid.equals(Ci.nsIObserver) &&
    1.28 +          !iid.equals(Ci.nsISupportsWeakReference) &&
    1.29 +          !iid.equals(Ci.nsISupports))
    1.30 +        throw Cr.NS_ERROR_NO_INTERFACE;
    1.31 +      return this;
    1.32 +    }
    1.33 +  },
    1.34 +  observe: {
    1.35 +    value: function(subject, topic, data) {
    1.36 +      emit(this, "data", {
    1.37 +        type: topic,
    1.38 +        target: subject,
    1.39 +        data: data
    1.40 +      });
    1.41 +    }
    1.42 +  }
    1.43 +}));
    1.44 +
    1.45 +function observe(topic) {
    1.46 +  let observerChannel = new ObserverChannel();
    1.47 +
    1.48 +  // Note: `nsIObserverService` will not hold a weak reference to a
    1.49 +  // observerChannel (since third argument is `true`). There for if it
    1.50 +  // will be GC-ed with all it's event listeners once no other references
    1.51 +  // will be held.
    1.52 +  addObserver(observerChannel, topic, true);
    1.53 +
    1.54 +  return observerChannel;
    1.55 +}
    1.56 +
    1.57 +exports.observe = observe;

mercurial