Search code examples
javascriptdom-events

Why use bind and unbind events to an elements in JavaScript?


I have a question about the binding and unbinding events to elements in JavaScript. I understand this: we bind and unbind elements to a elements when we create an element and this do something so we bind an event and when the user delete this element with and action the event listener needs to be remove because the element was removed, this is was I think, so my question is I am correct? Or when and why we bind and unbind events.


Solution

  • The reasons of when and why to bind an event are too numerous to list here (probably the former is more broad than the latter).

    However, 'we' as programmers use functions such as bind() so that our code may listen to events that occur on a particular element.

    unbind() is used when we no longer need to receive callbacks that an element has received such an event.

    As to when we use bind() and unbind() depends entirely upon the project and requirements for the event. Sometimes the events will be bound upon the creation of an element. Sometimes they'll be bound by a trigger (such as a user clicking a widget, for example), and sometimes they will be bound by the response of an AJAX call (or similar server-side callback). Similarly, we may use unbind() inside of a callback from another event, or when something happens on the server.

    As you can see, there is no "definitive" answer to when we use bind() and unbind(). However, you're slightly incorrect in your statement that unbind() is used when an element is removed. That is not necessary, when the element is removed, its event bindings are automatically discarded.