在浏览网页寻找Javascript自定义事件的解决方案时,我找不到任何实际的例子,甚至MDN资源也非常有限。
我正在尝试重建paperjs' onMouseDrag event。我的目的是用于类似油漆的网络应用程序。
onMouseDrag事件在以下时间触发:
此处的目标是不以便有一个有效的onMouseDrag
事件。目标是明确解释和示例如何创建CustomEvent
。 onMouseDrag
事件仅作为示例。
new CustomEvent()
或new Event()
,而不是任何弃用的方法。我尝试了以下
var onMouseDrag = new CustomEvent('mousedrag'),
elem = document.getElementById('element'),
mousedown = false;
elem.addEventListener('mousedrag', function (event) {
// The event argument passed should be
// the same event as the event passed by any other mouse event.
// Do something while the mouse is being dragged.
});
elem.addEventListener('mousedown', function (event) {
mousedown = true;
});
elem.addEventListener('mouseup', function (event) {
mousedown = false;
});
elem.addEventListener('mousemove', function (event) {
if (mousedown) {
elem.dispatchEvent('mousedrag');
// Pass the event variable to the dispatched mousedrag.
}
});
答案 0 :(得分:4)
你几乎得到了它,但你已经发送了你创建的原始事件,而不是字符串
var onMouseDrag = new CustomEvent('mousedrag'),
elem = document.getElementById('element'),
mousedown = false;
elem.addEventListener('mousedrag', function (event) {
console.log(event)
});
elem.addEventListener('mousedown', function (event) {
mousedown = true;
});
elem.addEventListener('mouseup', function (event) {
mousedown = false;
});
elem.addEventListener('mousemove', function (event) {
if (mousedown)
elem.dispatchEvent(onMouseDrag);
});
修改强>
似乎您只需向事件对象添加属性
即可var onMouseDrag = new CustomEvent('mousedrag'),
elem = document.getElementById('element'),
mousedown = false;
elem.addEventListener('mousedrag', function (event) {
var div = document.createElement('div');
div.className = 'point';
div.style.top = (event.clientY-71) + 'px';
div.style.left = (event.clientX-41) + 'px';
elem.appendChild(div);
});
elem.addEventListener('mousedown', function (event) {
mousedown = true;
});
elem.addEventListener('mouseup', function (event) {
mousedown = false;
});
elem.addEventListener('mousemove', function (event) {
if (mousedown) {
onMouseDrag.clientX = event.clientX;
onMouseDrag.clientY = event.clientY;
elem.dispatchEvent(onMouseDrag);
}
});
答案 1 :(得分:1)
要向事件对象添加更多数据,存在CustomEvent接口,并且detail属性可用于传递自定义数据。 例如,可以如下创建事件:
const event = new CustomEvent('build', { detail: elem.dataset.time });
然后,这将允许您在事件侦听器中访问其他数据:
function eventHandler(e) {
console.log('The time is: ' + e.detail);
}