-
-
Save boazsender/961057 to your computer and use it in GitHub Desktop.
/* | |
usage: | |
$.bind('customEvt', function( event ){ | |
console.log( event ); | |
}); | |
$.trigger('customEvt'); | |
*/ | |
;(function ($) { | |
$.bind = function( type, data, fn ){ | |
if ( arguments.length === 2 || data === false ) { | |
fn = data; | |
data = undefined; | |
} | |
jQuery.event.add( document, type, fn, data ); | |
}; | |
$.trigger = jQuery.event.trigger; | |
})( jQuery ); |
Re: $.bind... please re-read above.
I realize that
$.bind === Function.prototype.bind; // true
get it? its not "just a property" its a fundamental jQuery-will-not-do-it deal breaker.
Additionally, your most recent example is not handling custom data correctly, See: http://jsfiddle.net/rwaldron/jEU3w/
"not very jQuery"? What then, would be "jQuery" enough for you?
As for "overloads", the whole point of the 1.7 events re-write is to stop doing major overloads and create straight forward behaviours that are both backwards compatible and future proof.
rmurphy: I agree, we should be using an of DOM event pubsub object for managing subscriptions. My thinking is that in the event.js rewrite an overload would be provided in jQuery.event.add() that allows for not passing a DOM element, in which case events would get added to a pubsub-only object.
I realize that jQuery is a DOM-centric library, but a lot of people use jQuery which gives it the power to teach people good practices, and providing a documented jQuery style way of doing pubsub could lead users to do off DOM events well.
Imagine using the jQuery event like so
$.bind('customEvt', function( e ){
console.log( e.data ); // my message
console.log( e.type ); // customEvt
});
$.trigger('customEvt', 'my message');
e.data and e.type are familiar to jQuery users. I feel like extending this familiar API to pubsub would be enormously influential, and if it's only ~10 lines of code, it might be worth it.
I also have some ideas about jQuery managing event bubbling off DOM which I'm still thinking through.