Use jQuery functions as an event

I want to know if adding callbacks in jQuery is possible for operations with dom:

  • Append
  • before the name
  • addClass
  • toggleClass
  • removeClass
  • Val
  • text
  • CSS
  • atr
  • 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 have looked . queue and jQuery.Callback , but it will only work if I created my own wrapper for these functions?

Perhaps jQuery plugins?

It can be done without changes, all my js calls this plugin? Something is wrong:

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

Thanks.

+4
source share
2 answers

I don't know anything built-in that does this, but you can do it yourself, iterating through jQuery.fn (i.e. you would override these 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 just need to add / remove callbacks to the corresponding entry in the callbacks object.

Update: I don’t know what I don’t see here, but I can’t make an example , (Edit: ah, a classic error that forgets to wrap variables in closure ... it should work now. Also, an excluded list is added for functions that should not be overridden )

+1
source

You might be able to peek into jQuery.Deferred ... I think this is something like this ...

 $(function(){ $.when($('#one').hide('slow')) .then(function () { $('#two').hide('slow') }) .then(function () { $('#three').hide('slow') }); }); 

http://api.jquery.com/category/deferred-object/

+1
source

Source: https://habr.com/ru/post/1414282/


All Articles