JSFiddle - React, Tailwind, and code Playground
by wangd933
HTML
<!doctype html>
<html>
<head></head>
<body>
<script>
var Event = {
on: function(eventName, cb){
if(this.handlers == undefined){
Object.defineProperty(this,"handlers",{
enumerable: false,
configurable: true,
writable: true,
value: {},
})
}
if(this.handlers[eventName] == undefined){
this.handlers[eventName] = []
}
if(cb instanceof Function){
this.handlers[eventName].push(cb)
}
},
emit: function(eventName, value){
if(this.handlers && this.handlers[eventName] && this.handlers[eventName] instanceof Array){
for(var i = 0; i < this.handlers[eventName].length; i++){
this.handlers[eventName][i](value)
}
}
}
}
Event.on("test", function(result){
console.log(result)
})
Event.on("test", function(){
console.log("test")
})
Event.emit("test", "hello world")
var person1 = {}
var person2 = {}
Object.assign(person1, Event)
Object.assign(person2, Event)
person1.on("call1", function(){
console.log("person1")
})
person1.on("call2", function(){
console.log("person2")
})
person1.emit("call1")
person1.emit("call2")
person2.emit("call1")
person2.emit("call2")
</script>
</body>
</html>