function toType(v) {
if (arguments.length === 1) {
var type = Object.prototype.toString.call(v);
return type.slice(8, type.length - 1);
}
}
function PubSup(options) {
if (options) {
this.options = options;
}
}
function ast() {
return toType(arguments[0]) === 'String' || toType(arguments[0]) === 'Array';
}
function aft() {
return toType(arguments[0]).indexOf('Function') !== -1 || toType(arguments[0]) === 'Array';
}
PubSup.prototype = {
constructor: PubSup,
$on: function () {
var args = arguments;
if (args.length && this.options) {
try {
if (ast(args[0]) && aft(args[1])) {
args[0] = toType(args[0]) === 'String' ? [args[0]] : args[0];
args[1] = toType(args[1]).indexOf('Function') !== -1 ? [args[1]] : args[1];
for (var w = 0; w < args[0].length; w++) {
if (/(.*)/.test(args[0][w])) {
if (toType(args[1][w]).indexOf('Function') !== -1) {
this.options[args[0][w]] = args[1][w];
}
}
}
}
} catch (err) {
}
}
},
$emit: function () {
var args = arguments;
if (args.length) {
try {
if (ast(args[0])) {
args[0] = toType(args[0]) === 'String' ? [args[0]] : args[0];
if (args[0]) {
var args_ = [...args].slice(1);
for (var w = 0; w < args[0].length; w++) {
if (this.options.hasOwnProperty(args[0][w])) {
var ef = this.options[args[0][w]];
if (toType(ef).indexOf('Function') !== -1) {
var rd = ef(...args_);
if (toType(rd) === 'Boolean' && rd) {
this.delete(args[0][w]);
}
return rd;
}
}
}
}
}
} catch (err) { }
}
},
off: function () {
var args = arguments;
if (args.length) {
try {
if (ast(args[0])) {
args[0] = toType(args[0]) === 'String' ? [args[0]] : args[0];
if (args[0]) {
for (var w = 0; w < args[0].length; w++) {
if (this.options.hasOwnProperty(args[0][w])) {
this.delete(args[0][w])
}
}
}
}
} catch (err) { }
}
},
delete: function () {
try { delete this.options[arguments[0]] } catch (err) { }
},
clear() {
if (this.options) {
this.options = {};
}
}
}
var PubSup= new PubSup({});
console.log(PubSup)
PubSup.$on('a',function(){
console.log(1);
return true;
})
PubSup.$on('ab',function(){
console.log(2);
})
PubSup.$emit('a');
PubSup.$emit('ab');
PubSup.off(['ab']);
PubSup.$emit('ab');
如图

