refactor: ginify Screen (#24677)
This commit is contained in:
parent
362da77c0a
commit
e6cf5906f6
5 changed files with 36 additions and 60 deletions
|
@ -1,10 +1,20 @@
|
|||
'use strict';
|
||||
const { createScreen } = process._linkedBinding('electron_common_screen');
|
||||
|
||||
import { createLazyInstance } from '@electron/internal/browser/utils';
|
||||
const { EventEmitter } = require('events');
|
||||
const { Screen, createScreen } = process._linkedBinding('electron_common_screen');
|
||||
let _screen: Electron.Screen;
|
||||
|
||||
// Screen is an EventEmitter.
|
||||
Object.setPrototypeOf(Screen.prototype, EventEmitter.prototype);
|
||||
|
||||
module.exports = createLazyInstance(createScreen, Screen, true);
|
||||
// We can't call createScreen until after app.on('ready'), but this module
|
||||
// exposes an instance created by createScreen. In order to avoid
|
||||
// side-effecting and calling createScreen upon import of this module, instead
|
||||
// we export a proxy which lazily calls createScreen on first access.
|
||||
export default new Proxy({}, {
|
||||
get: (target, prop) => {
|
||||
if (_screen === undefined) {
|
||||
_screen = createScreen();
|
||||
}
|
||||
const v = (_screen as any)[prop];
|
||||
if (typeof v === 'function') {
|
||||
return v.bind(_screen);
|
||||
}
|
||||
return v;
|
||||
}
|
||||
});
|
||||
|
|
|
@ -1,38 +0,0 @@
|
|||
import { EventEmitter } from 'events';
|
||||
|
||||
/**
|
||||
* Creates a lazy instance of modules that can't be required before the
|
||||
* app 'ready' event by returning a proxy object to mitigate side effects
|
||||
* on 'require'
|
||||
*
|
||||
* @param {Function} creator - Function that creates a new module instance
|
||||
* @param {Object} holder - the object holding the module prototype
|
||||
* @param {Boolean} isEventEmitter - whether or not the module is an EventEmitter
|
||||
* @returns {Object} - a proxy object for the
|
||||
*/
|
||||
|
||||
export function createLazyInstance (
|
||||
creator: Function,
|
||||
holder: Object,
|
||||
isEventEmitter: Boolean
|
||||
) {
|
||||
let lazyModule: Object;
|
||||
const module: any = {};
|
||||
for (const method in (holder as any).prototype) { // eslint-disable-line guard-for-in
|
||||
module[method] = (...args: any) => {
|
||||
// create new instance of module at runtime if none exists
|
||||
if (!lazyModule) {
|
||||
lazyModule = creator();
|
||||
if (isEventEmitter) EventEmitter.call(lazyModule as any);
|
||||
}
|
||||
|
||||
// check for properties on the prototype chain that aren't functions
|
||||
if (typeof (lazyModule as any)[method] !== 'function') {
|
||||
return (lazyModule as any)[method];
|
||||
}
|
||||
|
||||
return (lazyModule as any)[method](...args);
|
||||
};
|
||||
}
|
||||
return module;
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue