Here is how I author custom events:
var event = jQuery.Event('customEventName');
$(element).trigger(event);
Granted, you could simply do
$(element).trigger('eventname');
But the way I wrote allows you to detect whether the user has prevented default or not by doing
var prevented = event.isDefaultPrevented();
This allows you to listen to your end-user's request to stop processing a particular event, such as if you click a button element in a form but do not want to the form to post if there is an error.
I then usually listen to events like so
$(element).off('eventname.namespace').on('eventname.namespace', function () {
...
});
Once again, you could just do
$(element).on('eventname', function () {
...
});
But I've always found this somewhat unsafe, especially if you're working in a team.
There is nothing wrong with the following:
$(element).on('eventname', function () {});
However, assume that I need to unbind this event for whatever reason (imagine a disabled button). I would then have to do
$(element).off('eventname', function () {});
This will remove all eventname
events from $(element)
. You cannot know whether someone in the future will also bind an event to that element, and you'd be inadvertently unbinding that event as well
The safe way to avoid this is to namespace your events by doing
$(element).on('eventname.namespace', function () {});
Lastly, you may have noticed that the first line was
$(element).off('eventname.namespace').on('eventname.namespace', ...)
I personally always unbind an event before binding it just to make sure that the same event handler never gets called multiple times (imagine this was the submit button on a payment form and the event had been bound 5 times)