Created
September 22, 2022 23:10
-
-
Save cmbaughman/b51861b5100131645d8a27e47ba85acc to your computer and use it in GitHub Desktop.
Example of "inversion of control" or aspect oriented programming in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Container = { | |
_storage: {}, | |
register(key, deps, func) { | |
this._storage[key] = { deps, func }; | |
}, | |
get(key) { | |
if (!this._storage[key]) throw new Error(`Missing ${key}`); | |
const { func, deps } = this._storage[key]; | |
return (...args) => { | |
const resolvedDeps = deps.map((key) => this.get(key)); | |
return func(...resolvedDeps, ...args); | |
}; | |
}, | |
}; | |
/** | |
With that, we can start and register our dependencies. The first will be settings and then the Service. | |
*/ | |
// Example | |
Container.register('settings', , () => { | |
return { fb: { key: 'xxx' } } | |
}); | |
Container.register('client', ['settings'], (settings) => { | |
return new Service({ APIKey: settings().fb.key }); | |
}); | |
Container.register('postToFacebook', ['client'], async (client, message) => { | |
const result = await client().post(message); | |
return result; | |
}); | |
// Then to use our new dependency injection container | |
const publish = container.get('postToFacebook'); | |
publish('What a beautiful day!'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment