Reputation: 7969
What is the difference between these two pieces of code? Both are working perfectly, so why use .dropdown.data-api in a function? I read about namespace on the internet, but I am not clear about that. Can anyone tell me what is the use of namespace functions?
$('html').on('click.dropdown.data-api',
function () {
$el.parent().removeClass('open')
})
}
$('html').on('click',
function () {
$el.parent().removeClass('open')
})
}
Upvotes: 5
Views: 257
Reputation: 34556
Namespacing an event allows you to target a particular event should you wish to, say, unbind or trigger it.
Imagine you have two events of the same kind bound to the same element(s).
$('.something').on('click', function() { /* do something */ });
$('.something').on('click', function() { /* do something else */ });
Since we didn't namespace either event, it is now difficult to unbind or trigger one but not the other. Now consider:
$('.something').on('click.one', function() { /* do something */ });
$('.something').on('click.two', function() { /* do something else */ });
Because this time each event has its own namespace, we can now trigger or unbind one or the other, leaving the other untouched.
$('.something').off('click.one'); //unbind the 'one' click event
$('.something').trigger('click.two'); //simulate the 'two' click event
[EDIT - as @jfrej right points out below, namespaces mean you sometimes don't even need to reference the event type name. So if you had a mouseover and click event both on a single namespace, you could unbind both with off('.namespace')
.]
Upvotes: 6