loader.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. 'use strict';
  2. const REGISTRATION_KEY = Symbol('@@any-observable/REGISTRATION');
  3. let registered = null;
  4. module.exports = (global, loadImplementation) => {
  5. return (implementation, opts) => {
  6. opts = opts || {};
  7. // global registration unless explicitly {global: false} in options (default true)
  8. const registerGlobal = opts.global !== false;
  9. // Load any previous global registration
  10. if (registerGlobal && !registered) {
  11. registered = global[REGISTRATION_KEY];
  12. }
  13. if (registered && implementation && registered.implementation !== implementation) {
  14. throw new Error(`any-observable already defined as "${registered.implementation}". You can only register an implementation before the first call to require('any-observable') and an implementation cannot be changed`);
  15. }
  16. if (!registered) {
  17. // Use provided implementation
  18. if (implementation && opts.Observable) {
  19. registered = {
  20. Observable: opts.Observable,
  21. implementation
  22. };
  23. } else {
  24. // Require implementation if implementation is specified but not provided
  25. registered = loadImplementation(implementation || null);
  26. }
  27. if (registerGlobal) {
  28. // Register preference globally in case multiple installations
  29. global[REGISTRATION_KEY] = registered;
  30. }
  31. }
  32. return registered;
  33. };
  34. };