Javascript 如何将EventEmitter2附加到div元素
我是EventEmitter2的新手。我的理解是,如果你想收听某个活动,你可以这样做:Javascript 如何将EventEmitter2附加到div元素,javascript,Javascript,我是EventEmitter2的新手。我的理解是,如果你想收听某个活动,你可以这样做: var EventEmitter2 = require('eventemitter2'); var server = new EventEmitter2(); server.on('touchend', test); // listen for event server.emit('touchend'); // fire off event function test() { console.log('h
var EventEmitter2 = require('eventemitter2');
var server = new EventEmitter2();
server.on('touchend', test); // listen for event
server.emit('touchend'); // fire off event
function test() { console.log('hello'); }
我不明白的是如何将发射器连接到div?在我的.js文件中,我得到了div元素,我想在该元素上附加一个侦听器,这样当用户单击它时我就知道了。我在找这样的东西:
someDIV.on('touchend', test)
function test() { console.log('hello'); }
server.on('gotAjax', function() {
console.log(arguments);
});
//...far far at some other scope, where is only server from prev code is accessible ....
function DataRecveived(data) {
render(data);
server.emit('gotAjax', data); // I not remember if need to "new Event()" here
您应该从浏览器中获取真实事件并将其发送到服务器。EventEmitter的意义是在脚本的逻辑部分进行基于事件的通信。例如,您的程序通过ajax获取数据,您希望在类似console.log()的东西中获取通知;所以你可以这样做:
someDIV.on('touchend', test)
function test() { console.log('hello'); }
server.on('gotAjax', function() {
console.log(arguments);
});
//...far far at some other scope, where is only server from prev code is accessible ....
function DataRecveived(data) {
render(data);
server.emit('gotAjax', data); // I not remember if need to "new Event()" here
所以在你的情况下,你应该像
someDIV.addEventListener('touchend', function() {
server.emit('touchEnd');
});
或者,如果您需要使用div在服务器上发射touchend来执行某些操作:
server.on('touchend') {
someDiv.classList.remove('touched');
}
谢谢你的帮助。问题是'someDiv'不是eventEmitter2的实例,而是一个div,因此它没有'on'函数。我试图找到一种方法,将eventEmitter2实例与div一起使用,但似乎不可能。我编辑了答案,addEventListener是本机事件处理程序;)