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?
2 Answers 2
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().
2 Comments
touchstart should be fine, afaik - just attach it with the advanced event model. A library like jQuery can help a lot with attaching and managing event handlers, because it hides browser differences. (and I'm sure you meant simply doStuff without parentheses)It's not a best practice but you can do something like this:
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');
var oldonmousedown = window.onmousedown;
/* add things to the sidebar */
window.onmousedown = function(e){
sidebar.id = "clicked";
oldonmousedown()
}
}
var createMenu();
var createSidebar();
But you should be using addEventListener() or attachEvent() like in bažmegakapa's answer
addEventListenerand (for IE)attachEvent, or, much easier .. jQuery [or your choice of framework] :)