New Feature?
New Feature?
Cheers jQueriers,
I'm a new member here. Our company is thinking about standardizing on
jQuery as our core JS platform and I've been doing some extensive
analysis on the library to make sure it meets our needs. I have to say
I'm really really impressed with the performance and ease of use - you
guys have done really stellar work!
One of our JS requirements is to encourage use of OO code as we create
our dynamic portal elements. After using jQuery for a while I found
that using bind to signal methods on object instances was kinda
cumbersome, so I devised a way to deal with this a little more nicely.
I added two functions to jQuery.fn: connect and disconnect. Code:
jQuery.fn.extend({
bind: function( type, data, fn ) {
return type == "unload" ? this.one(type, data, fn) :
this.each(function(){
jQuery.event.add( this, type, fn || data, fn && data );
});
},
connect: function( type, obj, method, args ) {
return this.each(function(){
var f = function(){ typeof method == 'string' ?
obj[method].apply(obj, args || [this] ) : method.apply.(obj, args ||
[this] ) ; }
var ccache = jQuery.data(this,'connect:'+type) || [];
ccache.push([obj,method,f]);
jQuery.data(this,'connect:'+type,ccache);
$(this).bind(type,f);
});
},
disconnect: function( type, obj, method ) {
return this.each(function(){
var ccache = jQuery.data(this,'connect:'+type) || [];
var hdlrs = [];
var ncache = [];
var elmt = this;
jQuery.each(ccache,function(i,rec) {
if (rec[0]==obj && rec[1]==method)
hdlrs.push(rec[2]);
else
ncache.push(rec);
});
jQuery.each(hdlrs,function(i,hdlr) { $
(elmt).unbind(type,hdlr); } );
jQuery.data(this,'connect:'+type,ncache.length ? ncache :
false);
});
},
...
This enables you to do things like:
function Comp(){}
Comp.prototype.vanish = function (elem)
{
$(elem).hide();
}
var c = new Comp();
$("#component1").connect( 'click', c, 'pickup' );
Even more excitingly, you can do things like:
$("#component0").connect( 'click', $('#component1') , "hide",
['fast'] );
$("#component2").connect( 'click', $('#component1') , "show",
['slow'] );
... this enables me to connect certain events to other jquery instance
methods without needing to create a callback. It's just a little
cleaner and makes the code a little easier to understand for certain
developers (who don't really understand how anonymous closures work).
Anyway, if you guys are agreeable, I'd like to submit a patch. Or you
can tell me why this idea isn't as cool as I think it is. Thanks!
Michael