官术网_书友最值得收藏!

Solution #3 - remove the handler

We may go for a lateral kind of solution, and instead of having the function avoid repeated clicks, we might just remove the possibility of clicking altogether:

function billTheUser(some, sales, data) {
document.getElementById("billButton").onclick = null;
window.alert("Billing the user...");
// actually bill the user
}

This solution also has some problems:

  • The code is tightly coupled to the button, so you won't be able to reuse it elsewhere
  • You must remember to reset the handler, otherwise the user won't be able to make a second buy
  • Testing will also be harder, because you'll have to provide some DOM elements

We can enhance this solution a bit, and avoid coupling the function to the button, by providing the latter's ID as an extra argument in the call. (This idea can also be applied to some of the following solutions.) The HTML part would be:

<button
id="billButton"
onclick="billTheUser('billButton', some, sales, data)"
>
Bill me
</button>;

(note the extra argument) and the called function would be:

function billTheUser(buttonId, some, sales, data) {
document.getElementById(buttonId).onclick = null;
window.alert("Billing the user...");
// actually bill the user
}

This solution is somewhat better. But, in essence, we are still using a global element: not a variable, but the onclick value. So, despite the enhancement, this isn't a very good solution either. Let's move on.

主站蜘蛛池模板: 崇阳县| 祥云县| 松阳县| 汝南县| 荥经县| 金坛市| 梨树县| 蒲江县| 桂东县| 禄丰县| 溧水县| 大荔县| 鄯善县| 安阳市| 平塘县| 台南县| 西乌珠穆沁旗| 巍山| 香格里拉县| 荥阳市| 乌兰察布市| 阿拉善盟| 义乌市| 翁牛特旗| 紫阳县| 甘肃省| 将乐县| 湘西| 化州市| 农安县| 梅河口市| 小金县| 上犹县| 宁德市| 台南市| 河东区| 依兰县| 阿荣旗| 遂溪县| 常宁市| 清徐县|