1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| window.onload = function() { var div1 = document.getElementById('div1'); var div2 = document.getElementById('div2'); addEvent(div1, 'click', function() { alert(1); }); addEvent(div2, 'show', function() { alert(2); }); fireEvent(div2, 'show'); } function addEvent(obj, events, fn) { obj.listeners = obj.listeners || {}; obj.listeners[events] = obj.listeners[events] || []; obj.listeners[events].push(fn); if (obj.addEventListener) { obj.addEventListener(events, fn, false); } else { obj.attachEvent('on' + events, fn); } }
function fireEvent(obj, events) { console.log(obj.listeners); for (var i = 0; i < obj.listeners[events].length; i++) { obj.listeners[events][i](); } }
|