JS Adapters Template
by maxell4o
HTML
<button adapter="telegrsam" config="eyJ0eXBlIjoidGVsZWdyYW0ifQ==">telegram</button>
<button adapter="facebook" config="eyJ0eXBlIjoiZmFjZWJvb2sifQ==">facebook</button>
<button adapter="twitter" wrong="eyJ0eXBlIjoidHdpdHRlciJ9">twitter</button>
JavaScript 1.7
class Actions {
constructor() {
this.adapters = {
telegram: this.telegram,
facebook: this.facebook,
twitter: this.twitter
};
this.listener.call(this);
}
telegram(config = Object, cb = Function) {
console.log('init:config', config);
setTimeout(() => {
cb({ ...config,
success: true
});
}, 2000);
}
facebook(config = Object, cb = Function) {
console.log('init:config', config);
setTimeout(() => {
cb({ ...config,
success: true
});
}, 2000);
}
twitter(config = Object, cb = Function) {
console.log('init:config', config);
setTimeout(() => {
cb({ ...config,
success: true
});
}, 2000);
}
listener() {
document.querySelectorAll('button').forEach(btn => btn.addEventListener('click', e => {
try {
let attrAdapter = e.target.getAttribute('adapter');
let attrConfig = e.target.getAttribute('config');
let adapter = this.adapters[attrAdapter];
let config = JSON.parse(atob(attrConfig || '') || null);
if (!adapter) {
throw (`Adapter of type "${attrAdapter}" is not defined!`);
}
if (config === null) {
throw (`Config for adapter "${attrAdapter}" is incorrect!`);
}
adapter.call(this, config, this.callback);
} catch (err) {
console.error(err);
}
}));
}
callback(args) {
console.log('callback', args);
}
}
new Actions();