如何检查事件传播是否已停止?

时间:2014-03-01 09:47:52

标签: javascript events

我正在用JavaScript编写一个事件调度程序,我决定基于标准的js CustomEvent类。如果事件传播在侦听器中停止(通过e.stopPropagation()),我无法找到如何检测。我应该自己编写一个Event对象实现吗?

4 个答案:

答案 0 :(得分:8)

据我所知,除了窥探Event.prototype.stopPropagation功能外,别无他法。

答案 1 :(得分:3)

如果属性cancelable设置为true并且使用了事件的preventDefault()方法,则CustomEvent将具有布尔属性defaultPrevented

var evt = new CustomEvent("custom", {cancelable : true});
console.log(evt.defaultPrevented);
evt.preventDefault();
console.log(evt.defaultPrevented);

Browser Support:Chrome 18,IE 9,Edge,Opera 11,Safari 5.

答案 2 :(得分:1)

您有两种可能的解决方案:

第一个解决方案

Event.cancelBubble 属性是 Event.stopPropagation() 的历史别名。但这与功能Event.stopPropagation()有所不同,因为Event.cancelBubble我们可以这样读:

var isPropagationStopped = event.cancelBubble; // true if it was stopped, or false if not

下一个解决方案

您可以在基本Event对象上覆盖stopPropagation方法,并在覆盖的方法中设置自己的标志,如下所示:

var isPropagationStopped = false;

var stopPropagationFuncTemp =  Event.prototype.stopPropagation;
Event.prototype.stopPropagation = function()
{
    isPropagationStopped = true;
    stopPropagationFuncTemp.apply(this, arguments);
};

现在,如果isPropagationStopped == true则停止。

答案 3 :(得分:-4)

你试过吗?

e.isPropagationStopped()

或者

event.isPropagationStopped()
相关问题