Search code examples
javascriptjqueryjquery-callback

Use jQuery functions as event


I wanna know if is possible append callbacks to jQuery for dom operations:

  • append
  • prepend
  • addClass
  • toggleClass
  • removeClass
  • val
  • text
  • css
  • attr
  • html
  • hide
  • etc

Something that works like new events.

Example:

$('#mydiv').bind('hide', function(){
    console.debug('someone call hide function')
});

//then in other js file, other function, anywhere.
$('#mydiv').hide();
//hide and output 'someone call hide function'

I looked at .queue and jQuery.Callback, but it only will work if I made my own wrapper for this functions?

Maybe jQuery plugins?

This can be done without change all my js calls this plugin? Something that is not like this:

$('#mydiv').myPluginsHide();

Thanks.


Solution

  • I don't know anything built-in that does that, but you could do it yourself by iterating over jQuery.fn (i.e. you would be overriding those functions as Felix Kling suggested):

    var callbacks = {};
    var excluded = ['constructor','init','jquery'];
    for ( var key in $.fn ) {
        var orig = $.fn[key];
        if ( !orig instanceof Function || excluded.indexOf(key) != -1 )
            continue;
        (function(key,orig) {
            callbacks[key] = []; // This is the list of callbacks for this function
            $.fn[key] = function() {
                var ret = orig.apply(this,arguments); // Applies the function normally
                var elements = this, args = arguments;
                callbacks[key].forEach(function(f) { f(elements, args); }); // Calls each callback
                return ret;
            };
        })(key,orig);
    }
    

    Then you'd just have to add/remove callbacks to the corresponding entry in the callbacks object.

    Update: don't know what I'm missing here, but can't make the example work. (Edit: ah, the classic mistake of forgetting to wrap your variables in a closure... it should work now. Also added an excluded list, for functions that must not be overriden).