You really want to be able to add all your event listeners in the same place; why? Simply for ease-of-maintenance.
Because of this, the best place to put all your event listeners is in a place where you can guarantee all elements you'll possibly want to bind event handlers to are available.
This is why the most common place to bind your event handlers is after the DOMReady
event has fired $(document).ready()
.
As always, there are some exceptions to the rule. Very occasionally, you might want to bind an event handler to an element as soon as it is available; which is after the closing tag of the element has been defined. In this instance, the following snippet should be used:
<div id="arbitrary-parent">
<h1 id="arbitrary-element">I need an event handler bound to me <strong>immediately!</strong></h1>
<script>document.getElementById("arbitrary-element").onclick = function () { alert("clicked"); }</script>
</div>
The other thing you should consider is how you are going to bind your handlers. If you stick to: DOMElement.onclick = function () { };
, you're limiting yourself to binding on handler per event.
Instead, the following approach allows you to bind multiple handlers per event:
function bind(el, evt, func) {
if (el.addEventListener){
el.addEventListener(evt, func, false);
} else if (el.attachEvent) {
el.attachEvent('on' + evt, func);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…