javascriptjqueryfunctionextending

How to add additional event handler in jQuery or plain javascript?


I have my own object with onShow() function, which is called (by me) when object is shown. I can override this function by assignment

o.onShow = function() { // something };

But it removes previous version of a function. So, if I wish to conserve existing handler, I should cache it and call in new handler:

o.oldOnShow = o.onShow;
o.onShow = function() { this.oldOnShow(); // something };

But this way I can cache only one previous handler. What if there are many of them?

Is there a convenient way to accomplish this task? How this task is named in literature? Is there a methods for this in jQuery?


Solution

  • If you need to trigger a custom event (as in defined by you), you should call the .trigger() method (whenever you feel that event should be triggered):

    $(o).trigger('my-awesome-event');
    

    Then you define one or more listeners, using either .bind() or (if you're using jQuery 1.7+) .on():

    $(o).on('my-awesome-event', function(event){ ... });