[英]In JavaScript button events, how do I avoid code duplication (when every button has similar functions)
I'm new to JavaScript and am trying to find out how to avoid using duplicate code for event listeners.我是 JavaScript 的新手,我正在尝试找出如何避免对事件侦听器使用重复代码。
I have a html page with a few buttons.我有一个带有几个按钮的 html 页面。
In this example with 2 buttons, (id'd trip_1 and trip_2 ) I want to have the button flash blue when clicked and then move on to the next step of the code after a few milliseconds在这个带有 2 个按钮的示例中,(id'd trip_1和trip_2 )我希望按钮 flash 在单击时变为蓝色,然后在几毫秒后继续执行代码的下一步
The code works, but has too much repitition.该代码有效,但重复过多。
Here I get a const for every button and then add an event listener to it.在这里,我为每个按钮获取一个 const,然后为其添加一个事件侦听器。 The listener does almost the same.听者做的几乎一样。
Is there a recommended way to avoid writing repeated listeners for every button?有没有推荐的方法来避免为每个按钮编写重复的侦听器?
I'd prefer having a single event listener listen to all buttons and then react to the one pressed.我宁愿让一个事件监听器监听所有按钮,然后对按下的按钮做出反应。
let step_change_ms = 250
function setCurrentStep(step) {
// removed, this function hides the elements not in use and
// shows the currently needed ones
}
const tripButton1 = document.getElementById('trip_1');
tripButton1.addEventListener('click', event => {
event.preventDefault();
tripButton1.style.backgroundColor = "blue";
buttons_active = false;
myBooking.trips = 1;
setTimeout(function () {
setCurrentStep('step4')
}, step_change_ms);
setTimeout(function () {
tripButton1.style.backgroundColor = "white";
}, step_change_ms);
});
const tripButton2 = document.getElementById('trip_2');
tripButton2.addEventListener('click', event => {
event.preventDefault();
tripButton2.style.backgroundColor = "blue";
buttons_active = false;
myBooking.trips = 2;
setTimeout(function () {
setCurrentStep('step4')
}, step_change_ms);
setTimeout(function () {
tripButton2.style.backgroundColor = "white";
}, step_change_ms);
});
You could do something like this (although I don't love splitting the id to get the number, but this is the general idea):你可以做这样的事情(虽然我不喜欢拆分 id 来获取数字,但这是一般的想法):
let step_change_ms = 250 function setCurrentStep(step) { // removed, this function hides the elements not in use and // shows the currently needed ones } const myBooking = { trips: 0 }; document.querySelectorAll('[id^=trip_]').forEach((el) => { const [, num ] = el.id.split('_'); el.addEventListener('click', event => { event.preventDefault(); el.style.backgroundColor = "blue"; buttons_active = false; myBooking.trips = parseInt(num); console.log(myBooking); setTimeout(function () { setCurrentStep('step4') }, step_change_ms); setTimeout(function () { el.style.backgroundColor = "white"; }, step_change_ms); }); });
<button id="trip_1">1</button> <button id="trip_2">2</button>
Or, maybe better:或者,也许更好:
let step_change_ms = 250 function setCurrentStep(step) { // removed, this function hides the elements not in use and // shows the currently needed ones } const myBooking = { trips: 0 }; const addListener = (el, num) => { el.addEventListener('click', event => { event.preventDefault(); el.style.backgroundColor = "blue"; buttons_active = false; myBooking.trips = num; console.log(myBooking); setTimeout(function () { setCurrentStep('step4') }, step_change_ms); setTimeout(function () { el.style.backgroundColor = "white"; }, step_change_ms); }); } addListener(document.getElementById('trip_1'), 1); addListener(document.getElementById('trip_2'), 2);
<button id="trip_1">1</button> <button id="trip_2">2</button>
I think the solution is pretty much easy.我认为解决方案非常简单。 You need to create a separate parametrized function that changes behavior based on passed parameters.您需要创建一个单独的参数化 function 来根据传递的参数更改行为。 As an example, you may create a factory function that takes some parameters and returns a new function (event handler).例如,您可以创建一个工厂 function,它接受一些参数并返回一个新的 function(事件处理程序)。 The code will look like that:代码将如下所示:
function createEventListener(btn, trips) {
return function(event) {
event.preventDefault();
btn.style.backgroundColor = "blue";
buttons_active = false;
myBooking.trips = trips;
setTimeout(function () {
setCurrentStep('step4')
}, step_change_ms);
setTimeout(function () {
btn.style.backgroundColor = "white";
}, step_change_ms);
}
}
const tripButton1 = document.getElementById('trip_1');
tripButton1.addEventListener('click', createEventListener(tripButton1, 1));
const tripButton2 = document.getElementById('trip_2');
tripButton2.addEventListener('click', createEventListener(tripButton2, 2));
PS Please note, the example may have some typos as I did not verify it, but I hope that the idea is clear. PS请注意,这个例子可能有一些错别字,因为我没有验证它,但我希望这个想法是清楚的。
PPS it is not always good to try to write DRY ( https://uk.wikipedia.org/wiki/Don%27t_repeat_yourself ) code, but better focus on SOLID ( https://en.wikipedia.org/wiki/SOLID ) principles PPS 尝试编写 DRY ( https://uk.wikipedia.org/wiki/Don%27t_repeat_yourself ) 代码并不总是好的,但更好地关注 SOLID ( https://en.wikipedia.org/wiki/SOLID )原则
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.