Plug-in source code jquery.callback.js
Plug-in open source address: https://gist.github.com/4580276
/**
* @fileOverview This plug-in is used to add callback functions to jQuery methods. You can add any custom callback functions to class methods or instance methods without affecting the behavior of the original method
* @dependency jQuery1.7
* @author huhai
* @since 2013-01-21
*/
(function($){
$._callbacks = {};
$._callbacks_ = {};
$._alias = {};
$._alias_ = {};
$.extend({
/**
* @description Add a callback function to the method
* @param funcName: string The name of the function that needs to add a callback
* @param callback: function callback function (if you need to remove it, do not use anonymous methods)
* @param static: boolean whether it is a class method, the default is false
*/
addCallback : function(funcName, callback, static){
if("string" === typeof(funcName) && $.isFunction(callback)){
if(static === true){
if($[funcName] && $ .isFunction($[funcName])){
if(!this._callbacks[funcName]){
this._callbacks[funcName] = $.Callbacks();
}
this._callbacks [funcName].add(callback);
if(!$._alias[funcName]){
$._alias[funcName] = $[funcName];//Register the original class method
$[funcName] = function(){//Proxy class method;
var result = $._alias[funcName].apply(this, arguments);
$._callbacks[funcName].fireWith(this, arguments);
return result;
};
}
}
}else{
if($.fn[funcName] && $.isFunction($.fn[funcName] )){
if(!this._callbacks_[funcName]){
this._callbacks_[funcName] = $.Callbacks();
}
this._callbacks_[funcName].add(callback );
if(!$._alias_[funcName]){
$._alias_[funcName] = $.fn[funcName];//Register the original instance method
$.fn[funcName] = function(){//Proxy instance method;
var result = $._alias_[funcName].apply(this, arguments);
$._callbacks_[funcName].fireWith(this, arguments);
return result;
};
}
}
}
}
},
/**
* @description Remove the callback function added to the method
* @param funcName: string The function name of the added callback
* @param callback: function callback function
* @param static: boolean whether Is a class method, the default is false
*/
removeCallback: function(funcName, callback , static){
if("string" === typeof(funcName) && $.isFunction(callback)){
if(static === true){
if($[funcName] && $.isFunction($[funcName])){
if(this._callbacks[funcName]){
this._callbacks.remove(callback);
}
}
}else{
if($.fn[funcName] && $.isFunction($.fn[funcName])){
if(this._callbacks_[funcName]){
this._callbacks_.remove(callback);
}
}
}
}
}
});
})(jQuery);
Usage example:
HTML