gpt4 book ai didi

javascript - 延迟Javascript中的默认事件

转载 作者:行者123 更新时间:2023-12-03 13:19:03 24 4
gpt4 key购买 nike

我希望能够将事件的默认操作延迟到采取其他操作之前。

它的作用是:我正在尝试构建一种可重用的,不引人注目的方式来通过模态对话确认 Action 。关键的愿望 list 项是任何javascript处理程序均由脚本附加,而不是直接内联编写。

为了使它真正可重用,我想在不同类型的项目上使用它:html链接,复选框,甚至其他由javascript驱动的操作。对于纯HTML元素(例如链接或复选框),我希望它们优雅地降级,以便在不打开JavaScript的情况下可用。

这是我设想的实现方式:

<a href="/somelink/" class="confirm">Some Link</a>
_________

<script>
attachEvent('a.confirm','click', confirmAction.fire)

var confirmAction = (function(){
var public = {
fire: function(e){
e.default.suspend();
this.modal();
},
modal: function(){
showmodal();
yesbutton.onclick = this.confirmed;
nobutton.onclick = this.canceled;
},
confirmed: function(){
hidemodal();
e.default.resume();
},
canceled: function(){
hidemodal();
e.default.prevent();
}
}
return public;
})()

</script>

我知道 e.preventDefault函数,但是这将杀死默认 Action ,而没有让我恢复它的能力。显然,带有 defaultsuspendresume方法的 prevent对象是为了说明我想要的目的而组成的。

顺便说一句,如果有帮助,我正在使用 Ext.Core库进行构建。该库为处理事件提供了大量标准化。但是我真的很想学习Javascript中的一般原理。

谢谢!

最佳答案

要恢复,您可以尝试保存事件并重新触发它,设置一个标志,该标志可用于跳过调用suspend()的处理程序(在您的示例中为“confirmAction.fire”)。

<a href="/somelink/" class="confirm">Some Link</a>
_________

<script>
function bindMethod(self, method) {
return function() {
method.apply(self, arguments);
}
}
var confirmAction = (function(){
var public = {
delayEvent: function(e) {
if (e.suspend()) {
this.rememberEvent(e);
return true;
} else {
return false;
}
},
fire: function(e){
if (this.delayEvent(e)) {
this.modal();
}
},
modal: function(){
showmodal();
yesbutton.onclick = bindMethod(this, this.confirmed);
nobutton.onclick = bindMethod(this, this.canceled);
},
confirmed: function(){
hidemodal();
this.rememberEvent().resume();
},
canceled: function(){
hidemodal();
this.forgetEvent();
},
rememberEvent: function (e) {
if (e) {
this.currEvent=e;
} else {
return this.currEvent;
}
},
forgetEvent: function () {
delete this.currEvent;
}
}
return public;
})()

// delayableEvent should be mixed in to the event class.
var delayableEvent = (function (){
return {
suspend: function() {
if (this.suspended) {
return false;
} else {
this.suspended = true;
this.preventDefault();
return true;
}
},
resume: function () {
/* rest of 'resume' is highly dependent on event implementation,
but might look like */
this.target.fireEvent(this);
}
};
})();

/* 'this' in event handlers will generally be the element the listener is registered
* on, so you need to make sure 'this' has the confirmAction methods.
*/
mixin('a.confirm', confirmAction);
attachEvent('a.confirm','click', confirmAction.fire);
</script>

这仍然存在潜在的错误,例如它如何与其他事件侦听器交互。

关于javascript - 延迟Javascript中的默认事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1263327/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com