I’ve got a custom Javascript class that generates a JQuery mousedown callback. The mousedown callback is on $(document) and should really only be set for the first new instance, and not for any subsequent ones. I’ve got something like the following:
function myclass(arg){
this.arg = arg;
$(document).mousedown(function(down_event){
// start action
}).mouseup(function(){
// stop action
})
}
I’d like those callbacks to only register once in the event that multiple myclass instances are crated, and not at all if none are created.
There’s a jQuery function for that. Use
.one()to bind a handler to the first instance of an event raised on an element (in this casedocument).Updated. The changes (using named handlers rather than anonymous functions, putting events in a specific namespace) are to ensure that new instances of myclass don’t rebind to the event if they are created after the first one has finished being unbound.