Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

This appears to be a class on a Javascript event. What is it?

I just ran across some jQuery that looks like this:

$('.add-row').live('click.add', function() { 
    // do something
}

This appears to be binding to the 'click.add' event. I use custom events myself and think they're awesome, but doing git grep on our code base doesn't reveal any place where a custom event called click.add is triggered, and in any case, this behavior is triggered by a normal click. Nor do I see an .add class anywhere in the HTML.

I don't think you can have classes on Javascript events. Any idea what this odd bit of syntax is?

like image 294
Nathan Long Avatar asked Feb 01 '11 20:02

Nathan Long


2 Answers

See http://api.jquery.com/event.namespace/ and especially http://api.jquery.com/bind/:

If the eventType string contains a period (.) character, then the event is namespaced. The period character separates the event from its namespace. For example, in the call .bind('click.name', handler), the string click is the event type, and the string name is the namespace. Namespacing allows us to unbind or trigger some events of a type without affecting others. See the discussion of .unbind() for more information.

like image 165
ThiefMaster Avatar answered Oct 19 '22 23:10

ThiefMaster


This is a featured called namespaced events. In this example, add is a namespace. It is effectively a class for events, so that you can categorise them and handle/trigger them accordingly. For instance, you might write a plugin and give every event handler a namespace of myPlugin so that you can unbind them without removing the user's other event handlers:

$('a').bind('click.myPlugin', function(){ /*...*/ }); // bind with the myPlugin namespace
$('a').bind('click'), function() { /* ... */ }); // bind without a namespace
$('a').unbind('.myPlugin'); // only removes the first function

This works for trigger as well.

like image 37
lonesomeday Avatar answered Oct 19 '22 23:10

lonesomeday