- Mastering JavaScript Functional Programming
- Federico Kereki
- 214字
- 2021-07-02 22:41:10
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.
推薦閱讀
- 一步一步學Spring Boot 2:微服務項目實戰
- JavaScript前端開發模塊化教程
- Raspberry Pi for Python Programmers Cookbook(Second Edition)
- Python入門很簡單
- HTML5 Mobile Development Cookbook
- 軟件測試項目實戰之性能測試篇
- Java持續交付
- Blender 3D Incredible Machines
- Python高效開發實戰:Django、Tornado、Flask、Twisted(第3版)
- 編譯系統透視:圖解編譯原理
- Oracle JDeveloper 11gR2 Cookbook
- PhoneGap:Beginner's Guide(Third Edition)
- 劍指大數據:企業級數據倉庫項目實戰(在線教育版)
- Java Web開發就該這樣學
- Learning AngularJS for .NET Developers