Explanation of event namespacing logic?

Explanation of event namespacing logic?

I was wondering what would happen if I bound an event handler with multiple ("nested") namespaces. It seems to work:

jQuery(document).bind('click.ui.foo'function(){});

... And it follows that this will remove that event handler:

jQuery(document).unbind('click');

So will this:

jQuery(document).unbind('click.ui');

And this:

jQuery(document).unbind('click.ui.foo');

And, to my surprise and confusion, so does this (proof: http://jsbin.com/irufo3):

jQuery(document).unbind('click.foo.ui');

Surely that shouldn't be happening?

I had a peak in the source and saw that the namespaces are being alphabetically sorted in  jQuery.event.add (line ~1623) - 

handleObj.namespace namespaces.slice(0).sort().join(".");

I wonder, why do they need to be sorted?

Also, in the event-removing logic ( jQuery.event.remove), what's this? (line ~1718) -

if !all {
    // Namespaced event handlers
    namespaces type.split(".");
    type namespaces.shift();

    namespace new RegExp("(^|\\.)" 
        jQuery.mapnamespaces.slice(0).sort()fcleanup ).join("\\.(?:.*\\.)?""(\\.|$)")
}







Not sure what's going on there, but I think it could do with an additional comment?

Originally, I wasn't even sure that nested namespaces would be supported but it seems to attempt at accommodating them, but I'm still wondering about that initial thing - why does foo.ui remove ui.foo?

Also, FYI: we can save 20 bytes of code (in the min version too) by replacing  new RegExp​( with just RegExp​( . AFAIK, it's exactly the same -- as per the ES-spec:

15.10.3 The RegExp Constructor Called as a Function
15.10.3.1 RegExp(pattern, flags)
If  pattern is an object  R whose  [[Class]] property is  "RegExp" and  flags is  undefined, then return  R unchanged. Otherwise call the RegExp constructor ( 15.10.4.1), passing it the  pattern and  flags arguments and return the object constructed by that constructor. 


It's interesting that closure doesn't take care of this...

Anyway, I'd appreciate some details about the expected behaviour of events with multiple namespaces.

Thanks :)