How to disable Events for a while in Javascript or jQuery
I am wondering if you guys know different approach to disable an event for a while. Let me elaborate this more :
Lets say I have a div or button which has a subscriber to its onclick
event. To prevent the double click when the the methods are doing some ajax things, these are the some of the ways we can do :
- Disable the button till the method finishes its job
- Unbind till the methods finishes its job and then bind it again.
- Use some ki开发者_运维技巧nd of flagging system like boolean so it will prevent method from working more than once.
So is there any other ways, maybe some javascript tricks or jQuery tricks which is more efficient and better practice.
Thanks in advance.
I just add some class like 'disabled' to that div or button. And in my function registered to the onclick
event, I check if that class is present. If yes, just return.
Can't think of any other way other than what u have stated.
I think the boolean flag is quite an elegant solution, and you can keep it "contained" by using a property of the handler, like so:
$(someElement).click(myHandler);
function myHandler() {
if (!myHandler.inProgress) {
myHandler.inProgress = true;
// Do stuff
// Set it back to false later
}
}
I can't think of a more 'tricky' or 'elegant' solution, than the ones you listed.
what is so inefficient in disabling an element or removing a binding?
精彩评论