有没有办法减少使用事件委派的`addEventListener`的数量。 JavaScript的

时间:2018-04-10 23:08:42

标签: javascript

是否可以使用事件委派只有一个addEventListener。有人帮忙吗?

// Get  button

const btnAll = document.querySelector('#btnAll')
const btnUrfa = document.querySelector('#btnUrfa')
const btnRookies = document.querySelector('#btnRookies')

const show = document.querySelector('#show')
const show01 = document.querySelector('#show01')
const show1 = document.querySelector('#show1')
const show11 = document.querySelector('#show11')

// Listen for button click
btnAll.addEventListener('click', fetchAll)
btnUrfa.addEventListener('click', fetchUrfa)
btnRookies.addEventListener('click', fetchRookies)

function fetchAll() {

    fetch('/fetchDataAll')
        .then((resp) => resp.json()) // Transform the data into json
        .then(function (data) {
            show.innerHTML = ''
            let players = data.result; // Get the results
            return players.forEach(function (player) {
                $("#show").append(`<p style='color:#FFFFFF'>${player.playerName}</p>
                <p style='color:#FFFFFF'>${player.teamName}</p>
                <h3 style='color:#66FF13'>+ ${player.scoreChange} %</h3>`)
            });
        })
        .catch(function (error) {
            console.log(error);
        });

    fetch('/fetchDataAll01')
        .then((resp) => resp.json()) // Transform the data into json
        .then(function (data) {
            show01.innerHTML = ''
            let players = data.result; // Get the results
            return players.forEach(function (player) {
                $("#show01").append(`<p style='color:#FFFFFF'>${player.playerName}</p>
                    <p style='color:#FFFFFF'>${player.teamName}</p>
                    <h3 style='color:#66FF13'>+ ${player.scoreChange} %</h3>`)
            });
        })
        .catch(function (error) {
            console.log(error);
        });

    fetch('/fetchDataAll1')
        .then((resp) => resp.json()) // Transform the data into json
        .then(function (data) {
            show1.innerHTML = ''
            let players = data.result; // Get the results
            return players.forEach(function (player) {
                $("#show1").append(`<p style='color:#FFFFFF'>${player.playerName}</p>
                    <p style='color:#FFFFFF'>${player.teamName}</p>
                    <h3 style='color:#D0021B'> ${player.scoreChange} %</h3>`)
            });
        })
        .catch(function (error) {
            console.log(error);
        });

    fetch('/fetchDataAll11')
        .then((resp) => resp.json()) // Transform the data into json
        .then(function (data) {
            show11.innerHTML = ''
            let players = data.result; // Get the results
            return players.forEach(function (player) {
                $("#show11").append(`<p style='color:#FFFFFF'>${player.playerName}</p>
                    <p style='color:#FFFFFF'>${player.teamName}</p>
                    <h3 style='color:#D0021B'> ${player.scoreChange} %</h3>`)
            });
        })
        .catch(function (error) {
            console.log(error);
        });
}

function fetchRookies() {

    fetch('/fetchDataRookies')
        .then((resp) => resp.json()) // Transform the data into json
        .then(function (data) {
            show.innerHTML = ''
            let players = data.result; // Get the results
            return players.forEach(function (player) {
                $("#show").append(`<p style='color:#FFFFFF'>${player.playerName}</p>
                <p style='color:#FFFFFF'>${player.teamName}</p>
                <h3 style='color:#66FF13'>+ ${player.scoreChange} %</h3>`)
            });
        })
        .catch(function (error) {
            console.log(error);
        });

    fetch('/fetchDataRookies01')
        .then((resp) => resp.json()) // Transform the data into json
        .then(function (data) {
            show01.innerHTML = ''
            let players = data.result; // Get the results
            return players.forEach(function (player) {
                $("#show01").append(`<p style='color:#FFFFFF'>${player.playerName}</p>
                    <p style='color:#FFFFFF'>${player.teamName}</p>
                    <h3 style='color:#66FF13'>+ ${player.scoreChange} %</h3>`)
            });
        })
        .catch(function (error) {
            console.log(error);
        });


    fetch('/fetchDataRookies1')
        .then((resp) => resp.json()) // Transform the data into json
        .then(function (data) {
            show1.innerHTML = ''
            let players = data.result; // Get the results
            return players.forEach(function (player) {
                $("#show1").append(`<p style='color:#FFFFFF'>${player.playerName}</p>
                    <p style='color:#FFFFFF'>${player.teamName}</p>
                    <h3 style='color:#D0021B'> ${player.scoreChange} %</h3>`)
            });
        })
        .catch(function (error) {
            console.log(error);
        });

    fetch('/fetchDataRookies11')
        .then((resp) => resp.json()) // Transform the data into json
        .then(function (data) {
            show11.innerHTML = ''
            let players = data.result; // Get the results
            return players.forEach(function (player) {
                $("#show11").append(`<p style='color:#FFFFFF'>${player.playerName}</p>
                    <p style='color:#FFFFFF'>${player.teamName}</p>
                    <h3 style='color:#D0021B'> ${player.scoreChange} %</h3>`)
            });
        })
        .catch(function (error) {
            console.log(error);
        });
}

function fetchUrfa() {

    fetch('/fetchDataUrfa')
        .then((resp) => resp.json()) // Transform the data into json
        .then(function (data) {
            show.innerHTML = ''
            let players = data.result; // Get the results
            return players.forEach(function (player) {
                $("#show").append(`<p style='color:#FFFFFF'>${player.playerName}</p>
                <p style='color:#FFFFFF'>${player.teamName}</p>
                <h3 style='color:#66FF13'>+ ${player.scoreChange} %</h3>`)
            });
        })
        .catch(function (error) {
            console.log(error);
        });

    fetch('/fetchDataUrfa01')
        .then((resp) => resp.json()) // Transform the data into json
        .then(function (data) {
            show01.innerHTML = ''
            let players = data.result; // Get the results
            return players.forEach(function (player) {
                $("#show01").append(`<p style='color:#FFFFFF'>${player.playerName}</p>
                    <p style='color:#FFFFFF'>${player.teamName}</p>
                    <h3 style='color:#66FF13'>+ ${player.scoreChange} %</h3>`)
            });
        })
        .catch(function (error) {
            console.log(error);
        });


    fetch('/fetchDataUrfa1')
        .then((resp) => resp.json()) // Transform the data into json
        .then(function (data) {
            show1.innerHTML = ''
            let players = data.result; // Get the results
            return players.forEach(function (player) {
                $("#show1").append(`<p style='color:#FFFFFF'>${player.playerName}</p>
                    <p style='color:#FFFFFF'>${player.teamName}</p>
                    <h3 style='color:#D0021B'> ${player.scoreChange} %</h3>`)
            });
        })
        .catch(function (error) {
            console.log(error);
        });

    fetch('/fetchDataUrfa11')
        .then((resp) => resp.json()) // Transform the data into json
        .then(function (data) {
            show11.innerHTML = ''
            let players = data.result; // Get the results
            return players.forEach(function (player) {
                $("#show11").append(`<p style='color:#FFFFFF'>${player.playerName}</p>
                    <p style='color:#FFFFFF'>${player.teamName}</p>
                    <h3 style='color:#D0021B'> ${player.scoreChange} %</h3>`)
            });
        })
        .catch(function (error) {
            console.log(error);
        });
}

1 个答案:

答案 0 :(得分:0)

首先,在按钮中添加一个公共类,例如"fetcher-btn"。然后向每个按钮添加一个数据属性(例如"data-fetcher"),指定他们将要执行的“抓取”类型("all""ufra""rookies")。然后在一个对象中对执行提取的函数进行分组,其中键是数据属性,值是函数。最后,将一个单击事件监听器添加到其中一个常用祖先按钮(最好是一个较近的按钮),在这里您可以检查所单击的元素是否具有类"fetcher-btn"(意味着它是我们的按钮之一)以及是否在它的数据属性存在,如果是,则调用该函数:

示例:

var fetcherObject = {                                          // the object that maps the data-fetcher attributes to their equivalent functions
  "all": fetchAll,
  "ufra": fetchUfra,
  "rookies": fetchRookies
};

document.addEventListener("click", function(ev) {              // add the click event listener to a common ancestor of the buttons (here document)
  var target = ev.target;                                      // get the target of the click event
  if(target.classList.contains("fetcher-btn")) {               // if the target is one of out buttons (has the class fetcher-btn)
    var fetchFn = fetcherObject[target.dataset.fetcher];       // use its data-fetcher (dataset.fetcher) value to get the function from fetcherObject
    if(fetchFn) {                                              // if that function exists (to make the test even strictier add typeof fetchFn === "function" and fetcherObject.hasOwnProperty(target.dataset.fetcher) checks)
      fetchFn();                                               // call the fetching function
    }
  }
});

function fetchAll() {
  console.log("fetchAll is called!");
}

function fetchUfra() {
  console.log("fetchUfra is called!");
}

function fetchRookies() {
  console.log("fetchRookies is called!");
}
<button class="fetcher-btn" data-fetcher="all">Fetch all</button>
<button class="fetcher-btn" data-fetcher="ufra">Fetch ufra</button>
<button class="fetcher-btn" data-fetcher="rookies">Fetch rookies</button>

注意:您的抓取功能可能会被重构并减少很多(因为它们似乎执行类似的任务),我建议您继续在CodeReviewSE上执行此操作(因为SO不适用于那种事情)。