我有以下代码重复一些模式
document.querySelector("form").addEventListener("submit",function(event){
event.preventDefault();
myFn.eventActionTrigger();
myFn.spinner("on");
});
document.querySelector("button").addEventListener("click",function(event){
event.preventDefault();
myFn.eventActionTrigger();
myFn.spinner("on");
});
document.querySelector(".seeMore").addEventListener("click",function(event){
event.preventDefault();
myFn.eventActionTrigger("seeMore");
myFn.spinner("on");
});
我怎样才能重构监听事件函数,使其具有一个泛型函数,该函数接受参数并依赖于它,监听权限事件并触发内部函数。
答案 0 :(得分:2)
您可以创建采用选择器,事件和回调函数的函数。
function action1() {alert('Form submited')}
function action2() {alert('Button clicked')}
function eventFunc(selector, event, callback) {
document.querySelector(selector).addEventListener(event, function(e) {
e.preventDefault();
callback()
})
}
eventFunc('form', 'submit', action1)
eventFunc('button', 'click', action2)

<form action=""><input type="submit" value="Submit"></form>
<button>click</button>
&#13;
如果要传递多个回调函数,可以在回调中使用rest参数并使用forEach
循环
function action1() {alert('Form')}
function another() {alert('Another function')}
function action2() {alert('Button')}
function eventFunc(selector, event, ...callback) {
document.querySelector(selector).addEventListener(event, function(e) {
e.preventDefault();
callback.forEach(c => c())
})
}
eventFunc('form', 'submit', action1, another)
eventFunc('button', 'click', action2)
&#13;
<form action=""><input type="submit" value="Submit"></form>
<button>click</button>
&#13;
答案 1 :(得分:1)
您可以使用闭包创建一个捕获参数(如传递给makeListener
方法的参数)的高阶函数myFn.eventActionTrigger
并返回一个自定义的事件监听器:
function makeListener(arg) {
return function (event) {
event.preventDefault()
myFn.eventActionTrigger(arg)
myFn.spinner('on')
}
}
document.querySelector('form').addEventListener('submit', makeListener())
document.querySelector('button').addEventListener('click', makeListener())
document.querySelector('.seeMore').addEventListener('click', makeListener('seeMore'))
// Boilerplate:
var myFn = {
eventActionTrigger: console.log.bind(console, 'eventActionTrigger:'),
spinner: console.log.bind(console, 'spinner:')
}
&#13;
<form>Form
<input type="submit">
</form>
<button>Button</button>
<div class="seeMore">See More</div>
&#13;
答案 2 :(得分:0)
这样的事情?
function addEventListener(selector, listenerType) {
document.querySelector(selector).addEventListener(listenerType, function(event){
event.preventDefault();
if (selector.charAt(0) === '.')
myFn.eventActionTrigger(selector);
else
myFn.eventActionTrigger();
myFn.spinner("on");
});
}
然后您将代码更新为:
addEventListener("form", "submit");
addEventListener("button", "click");
addEventListener(".seeMore", "click");