开发者

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

开发者 https://www.devze.com 2023-02-07 19:35 出处:网络
I just ran across some jQuery that looks like this: $(\'.add-row\').live(\'click.add\', function() { // do something

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 gr开发者_Python百科ep 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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消