Say I am writing a web-app, and I’d like to add certain behavior to a function after it has been declared in multiple places without overriding the old behaviors of the function.
Here is some simplified code (notice the window.onmousedown function
var createMenu = function(){
var menu = document.createElement('ul');
/* add things to the menu */
window.onmousedown = function(e){
menu.style.background = "red";
}
}
var createSidebar = function(){
var sidebar = document.createElement('div');
/* add things to the sidebar */
window.onmousedown = function(e){
sidebar.id = "clicked";
}
}
var createMenu();
var createSidebar();
In this case, window.onmousedown will not do both things it was meant to do – the definition it has in createSidebar will override its definition from createMenu. Is there a standard way of achieving a sort of behavior in which windows.onmousedown will retain both behaviors?
Use addEventListener() to add your events. It allows you to register multiple event handlers for an event on an element. Forget the old event model that you are using in your example.
For IE8 and older, you will have to use
attachEvent().Advanced event registration models on Quirksmode