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?


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.


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.

链接地址: http://www.djcxy.com/p/97010.html

上一篇: 如何从另一个.js文件调用.js?

下一篇: 这似乎是一个Javascript事件的类。 它是什么?