简体   繁体   中英

How do I combine two blocks of similar JavaScript Code?

I'm trying to find a way of writing some sort of function so that I don't have to keep rewriting the same type of code.

As you can see below, both blocks of code are pretty much the same except one is for the lunchTimeSelector and the other is for the napTimeSelector ? Is there any way to write a function so that I can just automate this by just inputting an array like [lunchTimeSelector, napTimeSelector, dinnerTimeSelector] , etc. into a function to replace this code?

// Activates Lunch selector
var lunchTimeSelector =  document.getElementById("lunchTimeSelector");

var lunchEvent = function()
{
    lunchtime = lunchTimeSelector.value;
};

lunchTimeSelector.addEventListener("change", lunchEvent);





// Activates Nap-Time selector
var napTimeSelector =  document.getElementById("napTimeSelector");

var napEvent = function()
{
    naptime = napTimeSelector.value;
};

napTimeSelector.addEventListener("change", napEvent);

You could implement it like so:

function addChangeEvent(id, handler){
    document.getElementById(id).addEventListener("change", handler);
}
[["lunchTimeSelector", function(){lunchtime = this.value}], 
 ["napTimeSelector", function(){naptime = this.value}]]
    .forEach(([id,handler])=>addChangeEvent(id,handler));

maybe you can try:

// wrap all your logic 
function lanuchNapTimeSelector(id,state){

 var target =  document.getElementById(id);

// your handelers
 var lunchEvent = function()
 {
    lunchtime = target.value;
 };

 var napEvent = function()
 {
    naptime = target.value;
 };

 target.addEventListener("change", state === "nap" ? napEvent : 
 lunchEvent);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM