1. (function($){
  2.  
  3. /* -----
  4.   * @author James Padolsey (http://james.padolsey.com)
  5.   * -----
  6.   * Extends jQuery's event facade by enabling you to
  7.   * pass just a 'data' object with no corresponding
  8.   * handler.
  9.   * E.g. $(elem).bind('click', {data:1})
  10.   * -----
  11.   * This data object is not treated as data in this
  12.   * situation. Its property names are treated as
  13.   * jQuery method names and its property values
  14.   * are treated as arguments to the associated
  15.   * jQuery method.
  16.   * -----
  17.   * Example usage:
  18.   * $(elem).bind('click', {
  19.   * addClass: 'clicked',
  20.   * css: {
  21.   * color: 'red'
  22.   * }
  23.   * });
  24.   * -----
  25.   * This extension is only activated when you pass
  26.   * a data object *without* a handler function for
  27.   * an event. If you pass the handler then the object
  28.   * will be treated as regular data; like before...
  29.   * -----
  30.   */
  31.  
  32. // Cache necessary methods:
  33. var _eventAdd = $.event.add,
  34. _eventBind = $.fn.bind,
  35. _eventOne = $.fn.one,
  36. _eventRemove = $.event.remove,
  37. uid = +new Date();
  38.  
  39. $.fn.bind = function(type, data, fn) {
  40. // Need a way to determine whether a handler
  41. // is passed; add secret key to data object:
  42. if (!fn) { data['__extended' + uid] = true; }
  43. // No handler? - Then add an empty one:
  44. fn = fn || (!$.isFunction(data) && function(){});
  45. // Bind it as usual:
  46. return _eventBind.call(this, type, data, fn);
  47. };
  48.  
  49. $.fn.one = function(type, data, fn) {
  50. // (Same as above)
  51. if (!fn) { data['__extended' + uid] = true; }
  52. fn = fn || (!$.isFunction(data) && function(){});
  53. return _eventOne.call(this, type, data, fn);
  54. };
  55.  
  56. $.event.remove = function(elem, types, handler) {
  57. if (handler && !$.isFunction(handler) && handler['__handler' + uid]) {
  58. handler = handler['__handler' + uid];
  59. }
  60. _eventRemove.call(this, elem, types, handler);
  61. };
  62.  
  63. $.event.add = function(elem, types, handler, data) {
  64. // If __extended prop is found, then its assumed
  65. // to be a non-data executable object:
  66. handler = data['__extended' + uid] ?
  67. function() {
  68. data['__handler' + uid] = handler;
  69. for (var i in data) {
  70. // Check whether the prop name is a
  71. // jQuery method before firing:
  72. $.fn[i] && $.fn[i].apply(
  73. $(this), $.isArray(data[i]) ? data[i] : [data[i]]
  74. );
  75. }
  76. } : handler;
  77. // Continue with core functionality:
  78. _eventAdd.call(this, elem, types, handler, data);
  79. };
  80.  
  81. })(jQuery);

ALL COPYRIGHT © James Padolsey unless otherwise specified
Go back to the top