wurzel_gummidge
wurzel_gummidge

Reputation: 277

How to attach and remove an event handler programmatically

Is there a simple and clear way of writing these 2 functions as a single function without duplication. I think I want to programmatically set the on/off method.

function attachEventHandler(){
   $(document).on({
      ajaxStart: function() {
         $("body").addClass("loading");
      },
      ajaxStop: function() {
         $("body").removeClass("loading");
      }
   });
}

function removeEventHandler(){
   $(document).off({
      ajaxStart: function() {
         $("body").addClass("loading");
      },
      ajaxStop: function() {
         $("body").removeClass("loading");
      }
   });
}

Upvotes: 0

Views: 255

Answers (2)

lordvlad
lordvlad

Reputation: 5347

Simplest answer that comes to my mind is

var handlers = {
      ajaxStart: function() {
         $("body").addClass("loading");
      },
      ajaxStop: function() {
         $("body").removeClass("loading");
      }
   }

function attachEventHandler(toggle){
   // here we are selecting the 'on' or 'off'
   // property of the $(document) jquery element
   // depending on whether the toggle is true or
   // false. Because the 'on' and 'off' props are
   // functions, we can call the property with
   // `handlers` as the argument
   $(document)[toggle ? 'on' : 'off'](handlers);
}

and use it like so:

attachEventHandler(true) // turn on
attachEventHandler(false) // turn off

Upvotes: 1

Abdulla
Abdulla

Reputation: 471

You can use .on() to bind a function to multiple events:

$('#element').on('keyup keypress blur change', function(e) {
// e.type is the type of event fired
});

Or just pass the function as the parameter to normal event functions:

var myFunction = function() {
...
}

$('#element')
.keyup(myFunction)
.keypress(myFunction)
.blur(myFunction)
.change(myFunction)

Upvotes: 0

Related Questions