Javascript 如何实现自定义事件对象的API?

Javascript 如何实现自定义事件对象的API?,javascript,object,ecmascript-6,dom-events,Javascript,Object,Ecmascript 6,Dom Events,如何实现自定义事件对象的API,以及note中显示的函数(测试1)。 extend需要重用事件对象的API(测试2) 因此,它不是一个代码编写服务。这看起来很像“请填补空白”。您能告诉我们您尝试了什么以及您的问题在哪里吗?假设这是在节点上,为什么不使用内置的呢? Event.on('test',function(result){ console.log(result); }) Event.on('test',function(){ console.log('test'); })

如何实现自定义事件对象的API,以及note中显示的函数(测试1)。 extend需要重用事件对象的API(测试2)


因此,它不是一个代码编写服务。这看起来很像“请填补空白”。您能告诉我们您尝试了什么以及您的问题在哪里吗?假设这是在节点上,为什么不使用内置的呢?
Event.on('test',function(result){
    console.log(result);
})
Event.on('test',function(){
    console.log('test');
})
Event.emit('test','hello world');//output 'test'和'hello world'
//test2
var person1 = {};
var person2 = {};
Object.assign(person1,Event);
Object.assign(person2,Event);
person1.on('call1',function(){
    console.log('person1');
});
person2.on('call2',function(){
    console.log('person2');
});
person1.emit('call1'); //output 'person1'
person1.emit('call1'); //not output
person1.emit('call1'); //not output
person1.emit('call1'); //output 'person2'

var Event= {
    //through on api watch event evenName
    //if event eventName was triggered,execute callback function
    on:function(eventName,callback){
        //your code
    },
    //trigger event eventName
    emit:function(eventName){
        //your code
    }
}
var Event = {
    on: function(eventName, callback){
      //todo
      if(!this[eventName])
      this[eventName] = [];
      this[eventName].push(callback);
   },
   emit: function(eventName){
   //todo
    if(this[eventName])
    Array.prototype.forEach.call(this[eventName], function(func){
      func.call(this);
    });
  }
}

Event.on("one", function(){
  console.log("go");
})
Event.on("one", function(){
  console.log("gogo");
})

Event.emit("one");

var person1 = Object.assign({}, Event);
var person2 = Object.assign({}, Event);
person1.on("666", function(){
  console.log("person1 666");
})
person2.on("777", function(){
  console.log("person2 777");
})

person1.emit("666");
person1.emit("777");
person2.emit("777");
person2.emit("666");