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

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.

主站蜘蛛池模板: 普宁市| 靖西县| 齐河县| 比如县| 澜沧| 克拉玛依市| 诸暨市| 昌邑市| 衡南县| 鄢陵县| 安陆市| 公主岭市| 玉屏| 东平县| 常州市| 陈巴尔虎旗| 洞头县| 甘谷县| 雅江县| 抚州市| 拜泉县| 平武县| 海安县| 陆河县| 正定县| 雷山县| 泰兴市| 蓬溪县| 德安县| 西昌市| 康平县| 鹤壁市| 靖边县| 古交市| 山东省| 宁明县| 荃湾区| 卢龙县| 无极县| 左权县| 德令哈市|