events.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. 'use strict';
  5. module.metadata = {
  6. 'stability': 'experimental'
  7. };
  8. let { request: hostReq, response: hostRes } = require('./host');
  9. let { defer: async } = require('../lang/functional');
  10. let { defer } = require('../core/promise');
  11. let { emit: emitSync, on, off } = require('../event/core');
  12. let { uuid } = require('../util/uuid');
  13. let emit = async(emitSync);
  14. // Map of IDs to deferreds
  15. let requests = new Map();
  16. // May not be necessary to wrap this in `async`
  17. // once promises are async via bug 881047
  18. let receive = async(function ({data, id, error}) {
  19. let request = requests.get(id);
  20. if (request) {
  21. if (error) request.reject(error);
  22. else request.resolve(clone(data));
  23. requests.delete(id);
  24. }
  25. });
  26. on(hostRes, 'data', receive);
  27. /*
  28. * Send is a helper to be used in client APIs to send
  29. * a request to host
  30. */
  31. function send (eventName, data) {
  32. let id = uuid();
  33. let deferred = defer();
  34. requests.set(id, deferred);
  35. emit(hostReq, 'data', {
  36. id: id,
  37. data: clone(data),
  38. event: eventName
  39. });
  40. return deferred.promise;
  41. }
  42. exports.send = send;
  43. /*
  44. * Implement internal structured cloning algorithm in the future?
  45. * http://www.whatwg.org/specs/web-apps/current-work/multipage/common-dom-interfaces.html#internal-structured-cloning-algorithm
  46. */
  47. function clone (obj) JSON.parse(JSON.stringify(obj || {}))