jQuery Live DOM sub/pub plugin

Updated 2/10/10 – for the updates to the plugin (See: here)

I made a new jQuery plugin the other day, it is pretty simple, it expands on the idea subscribe/publish idea. Basically it allows you to bind subscriptions to DOM nodes.

You use it like this:



//subscribe a node
$(selector).subscribe(
'subscription/name',
function(subName, [arg1], [arg2],...)
{/*do something*/}
);

//publish
$.publish(
'subscription/name', [arg1], [arg2],...
);

The idea is that you are probably using sub/pub to keep your DOM interaction separate from your non DOM related javascript. So, when you publish, there is a good chance that the subscriber will take the published information and do something to the DOM based on it. Inside of you sub callback, this is the DOM node following jQuerys normal pattern for this.

You can still setup normal subscriptions like so:


$.subscribe(
'subscription/name',
function(subName, [arg1], [arg2],...)
{/*do something*/}
);

One thing to note is that nothing is actually bound to the nodes. In reality the selector that you give is simply saved, and used again when you publish, so this works like .live in that it will even work on nodes added to the DOM after you subscribe. Also like .live though, you must provide the full selector as a string, and you can’t use any of the traversal methods to select your nodes.

Demo:

You must enter something here
Watch me.

The code for this is :


$('#formId').submit(function(e){
validateForm();
return false;
});

$('#response').subscribe('formValidateDone', function(subName, result) {
if(result) {
$(this).html('The form is valid!');
} else {
$(this).html('Please try again!');
}
});

function validateForm() {
$.publish('formValidateDone', $('#textInput').val() !== '');
}

Plugin Link: Plugin page

Download: Download

Leave a Reply

Your email address will not be published. Required fields are marked *