Mr Speaker

Selecting JavaScript objects with jQuery

After a bit of prodding around I've not only found out that selecting JavaScript objects and arrays with jQuery is fully supported, but there are also some potential use cases! It all started a couple of weeks ago when I thought it would be cool to bind custom events to actual JavaScript objects.

var foo = {};
$( foo ).bind( "fireOne", function({
    alert( "event is go!" );
});
$( foo ).trigger( "fireOne" );

And lo and behold, it worked. Not only with .bind and .trigger, but also with .data and inside plugins. Too weird to be true, I fired off a question to the jQuery Dev list where Mr John Resig himself confirmed:

It was unintentional - way back in the day - but we've come to embrace it. Expect those aforementioned methods (bind / unbind and data) to continue to work on plain JavaScript objects.

Cool, but why? And can we do anything really stupid with it? The first thing I had to try was $($). But of course, that's dumb, because typeof jQuery == function. And functions get executed as shortcuts to the ready function... so the interpreter spits the dummy with Error: too much recursion. Naturally. So next up, how about this? typeof jQuery.cache == Object! Ha ha! How about storing data against the object that stores data? Sure thing! $( $.cache ).data( "butWhy", 1234 ) works a treat. But, er. anyway...

Right-o. Is there any useful purpose for all this? I'm sure there's plenty. In fact, there's on thing that is in jQuery already. The $.extend method lets you mash two objects together (though the argument for the second needs to wrapped as jQuery object too). Let's make a simple version of that.

Simple object extending

Here's an example of how we could do a "shallow extend" with a plugin. We'll set up a shallow plugin that copies all the top level properties off one object on to the selected one, and use another plugin to log out all the properties so we can test it worked:

$.fn.shallow = function( obj ){
	return this.each( function(){
		for ( name in obj ) {
			if( this[ name ] === undefined ){
				this[ name ] = obj[ name ];
			}
		}
	});
}
$.fn.log = function(){
	return this.each(function(){
		for ( name in this ) {
			console.log( name, this[ name ] );
		}
	})
}

Next, we'll set up a couple of objects and mash them together with our plugins:

var one = {
	name: "I'm one"
};
var two = {
	name: "I'm two",
	jump: function(){}
};

$( one ).shallow( two ).log();

And the console will spit out { name: "I'm one", jump: function }. Which is pretty snazzy, but still pretty useless. The only place where I think you could argue in favour of this technique is if the wrapped code was "DOM specific" stuff, or where it acted as kind of a bridge between 3rd party objects...

Playing nicely with 3rd party objects

The weekend after I found out about wrapping objects I fell over a (perhaps) reasonable use case for them. It was 4.00am at the first #govhack event and the team I was working with were using Bing maps to plot some data as map markers. When the user clicked on the marker, an event would be fired so you'd know which marker was clicked - but not which of our custom JavaScript objects that marker related to! Hmmm. It's 4.00am... is this realllly a use case? I didn't know, but did it anyway.

The map API gives you back a "pin" object that contains information about the marker. I just attached the custom point object to the marker itself. Because it uses jQuery's cache, there is no danger of overwriting any of the 3rd parties properties - we don't change their object at all.

var pin = new VEShape( VEShapeType.Pushpin, latLong );
pin.data( "point", this );

map.AttachEvent( "onclick", shapeInfo );
shapeInfo : function( e ){
	shape = map.GetShapeByID(e.elementID);
	var point = $(shape).data("point");
}

When a click event is caught, we can grab the data back! Very handy!

So there you go. Perhaps it's not so crazy after all. I still think there is a "killer" idea in there waiting to be discovered. It's a pity that functions get shortcutted and exectued in jQuery, else we could build some crazy decorators and interface systems that wouldn't make any sense. Ah well.

2 Comments

  1. very cool & good tip, thank you very much for sharing.

    Can I share this post on my JavaScript library?

    Awaiting your response. Thank

    Monday, November 16, 2009 at 8:56 pm | Permalink
  2. The 1.4.2 release of jQuery has killed this “feature”. I want it back because we use this heavily to add custom events to standard js objects. See this post: http://forum.jquery.com/topic/javascript-error-when-unbinding-a-custom-event-using-jquery-1-4-2

    Wednesday, February 24, 2010 at 10:07 am | Permalink
Captcha! Please type 'radical' here: *
How did you find this thingo? *