1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/addon-sdk/source/lib/sdk/addon/events.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': 'experimental' 1.12 +}; 1.13 + 1.14 +let { request: hostReq, response: hostRes } = require('./host'); 1.15 +let { defer: async } = require('../lang/functional'); 1.16 +let { defer } = require('../core/promise'); 1.17 +let { emit: emitSync, on, off } = require('../event/core'); 1.18 +let { uuid } = require('../util/uuid'); 1.19 +let emit = async(emitSync); 1.20 + 1.21 +// Map of IDs to deferreds 1.22 +let requests = new Map(); 1.23 + 1.24 +// May not be necessary to wrap this in `async` 1.25 +// once promises are async via bug 881047 1.26 +let receive = async(function ({data, id, error}) { 1.27 + let request = requests.get(id); 1.28 + if (request) { 1.29 + if (error) request.reject(error); 1.30 + else request.resolve(clone(data)); 1.31 + requests.delete(id); 1.32 + } 1.33 +}); 1.34 +on(hostRes, 'data', receive); 1.35 + 1.36 +/* 1.37 + * Send is a helper to be used in client APIs to send 1.38 + * a request to host 1.39 + */ 1.40 +function send (eventName, data) { 1.41 + let id = uuid(); 1.42 + let deferred = defer(); 1.43 + requests.set(id, deferred); 1.44 + emit(hostReq, 'data', { 1.45 + id: id, 1.46 + data: clone(data), 1.47 + event: eventName 1.48 + }); 1.49 + return deferred.promise; 1.50 +} 1.51 +exports.send = send; 1.52 + 1.53 +/* 1.54 + * Implement internal structured cloning algorithm in the future? 1.55 + * http://www.whatwg.org/specs/web-apps/current-work/multipage/common-dom-interfaces.html#internal-structured-cloning-algorithm 1.56 + */ 1.57 +function clone (obj) JSON.parse(JSON.stringify(obj || {}))