- 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.
推薦閱讀
- Oracle Exadata性能優(yōu)化
- Interactive Data Visualization with Python
- 構(gòu)建移動網(wǎng)站與APP:HTML 5移動開發(fā)入門與實戰(zhàn)(跨平臺移動開發(fā)叢書)
- Learning AWS Lumberyard Game Development
- Python Network Programming Cookbook(Second Edition)
- Spring實戰(zhàn)(第5版)
- 軟件工程
- SharePoint Development with the SharePoint Framework
- KnockoutJS Starter
- Jupyter數(shù)據(jù)科學(xué)實戰(zhàn)
- Nginx實戰(zhàn):基于Lua語言的配置、開發(fā)與架構(gòu)詳解
- 深入淺出Go語言編程
- 軟件項目管理實用教程
- 深度實踐KVM:核心技術(shù)、管理運維、性能優(yōu)化與項目實施
- Python硬件編程實戰(zhàn)