473,778 Members | 1,886 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Two problems with "addEvent() " code

RMWChaos
137 New Member
I grabbed this "Rock Solid addEvent" code from this site, which is based on Mark Wubben's event-cache code. (These links for reference only.)

I am having two problems with it, and the webmaster is s...l...o...w to respond. So I thought I would ask about it here. If I knew more about how this code works, I could probably figure out most of the problems myself, but with this one, I am clueless! =D

First question: This may be my own unfamiliarity with attachEvent(), but I cannot seem to use addEvent() for onclick, onmouseover, and onmouseout. I tried just using attachEvent() directly, but got an error message that "object type does not support this method". Well, [insert favorite expletive here]!! So this code does not work for me:

Expand|Select|Wrap|Line Numbers
  1. addEvent(nodeid, 'click', myFunc);
  2.  
Second question: Why can I not pass a value in the function using this code? Example, I get an error with this:

Expand|Select|Wrap|Line Numbers
  1. addEvent(window, 'load', myFunc(value));
  2.  
And without further ado, here be the code (a long and nasty bugger):
Expand|Select|Wrap|Line Numbers
  1. function addEvent(obj, type, fn)
  2.      {
  3.      if (obj.addEventListener) // FireFox, NN, Mozilla, etc.
  4.           {
  5.           obj.addEventListener(type, fn, false);
  6.           // bugzilla bug #241518
  7.           EventCache.add(obj, type, fn);
  8.           }
  9.      else if (obj.attachEvent) // MSIE
  10.           {
  11.           var func = function()
  12.                {
  13.                fn.apply(window.event.srcElement);
  14.                };
  15.           obj.attachEvent("on" + type, func);
  16.           EventCache.add(obj, type, func);
  17.           }
  18.      else if (typeof obj['on' + type] != 'function')
  19.           {
  20.           obj['on' + type] = fn;
  21.           }
  22.      else // really old
  23.           {
  24.           var oldonload = obj['on' + type];
  25.           obj['on' + type] = function()
  26.                {
  27.                oldonload();
  28.                fn();
  29.                };
  30.           };
  31.      };
  32.  
  33. function removeEvent(obj, type, fn)
  34.      {
  35.      EventCache.remove(obj, type, fn);
  36.      };
  37.  
  38. var EventCache = function()
  39.      {
  40.      var listEvents = [];
  41.      return {
  42.           listEvents : listEvents,
  43.           add : function(node, sEventName, fHandler)
  44.                {
  45.                listEvents.push(arguments);
  46.                },
  47.           remove : function(node, sEventName, fHandler)
  48.                {
  49.                var i, item;
  50.                for(i = listEvents.length - 1; i >= 0; i = i - 1)
  51.                     {
  52.                     if(node == listEvents[i][0] && sEventName == listEvents[i][1] && fHandler == listEvents[i][2])
  53.                          {
  54.                          item = listEvents[i];
  55.                          if(item[0].removeEventListener)
  56.                               {
  57.                               item[0].removeEventListener(item[1], item[2], item[3]);
  58.                               };
  59.                          if(item[1].substring(0, 2) != "on")
  60.                               {
  61.                               item[1] = "on" + item[1];
  62.                               };
  63.                          if(item[0].detachEvent)
  64.                               {
  65.                               item[0].detachEvent(item[1], item[0][sEventName+fHandler]);
  66.                               };
  67.                          item[0][item[1]] = null;
  68.                          };
  69.                     };
  70.                },
  71.           flush : function()
  72.                {
  73.                var i, item;
  74.                for(i = listEvents.length - 1; i >= 0; i = i - 1)
  75.                     {
  76.                     item = listEvents[i];
  77.                     if(item[0].removeEventListener)
  78.                          {
  79.                          item[0].removeEventListener(item[1], item[2], item[3]);
  80.                          };
  81.                     if(item[1].substring(0, 2) != "on")
  82.                          {
  83.                          item[1] = "on" + item[1];
  84.                          };
  85.                     if(item[0].detachEvent)
  86.                          {
  87.                          item[0].detachEvent(item[1], item[2]);
  88.                          };
  89.                     item[0][item[1]] = null;
  90.                     };
  91.                }
  92.           };
  93.      }();
  94.  
Oh, and one last question...why the () at the very end of this code?
Nov 23 '07 #1
1 1866
Dasty
101 Recognized Expert New Member
The whole problem is about mixing 2 different things. You have to make clear when you are working with references to objects/functions and when you are working just with their results. As we may know:

Expand|Select|Wrap|Line Numbers
  1. myFunc   // is just reference to function with "myFunc" name
  2. myFunc() // is result of executing myFunc function
While keeping this in mind, we can answer most of your questions. addEvent(obj, type, fn) function is expecting 3 attributes
obj - REFERENCE to the DOM object
type - string representation of event name (without 'on')
fn - REFERENCE to your event handler function

So, first answer:
Expand|Select|Wrap|Line Numbers
  1. addEvent(nodeid, 'click', myFunc);
use
Expand|Select|Wrap|Line Numbers
  1. addEvent(document.getElementById('nodeid'), 'click', myFunc);
Second answer:
Expand|Select|Wrap|Line Numbers
  1. addEvent(window, 'load', myFunc(value));
In this calling, JS will execute myFunc function first and send it's return value as 3th parameter to addEvent function. So while your myFunc function is not returning reference to any other function, this code is invalid.

Third answer:
"why the () at the very end of this code"

Simple, creator dont want to assign function reference to EventCache. He wants to assign result of function execution to EventCache. Think of it that way:

Expand|Select|Wrap|Line Numbers
  1. var EventCache;
  2.  
  3. anonymousfunction = function()
  4. {
  5.  ... code here
  6.  
  7.  return something; 
  8. }
  9.  
  10. EventCache = anonymousfunction();
  11.  
so in the end EventCache is holding RESULT of running anonymousfuncti on.
Nov 23 '07 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

4
5376
by: Ben | last post by:
Hello everybody I got confused by this problem for which I don't have a logical explanation. There is a Thread (ThreadA) which receives Events from another system thread (ThreadS). ThreadA then adds a time stamp to the received event and adds it to a event queue. This works well (therfore not shown here). The queue fills up. Then I used a timer to check every millisecond for new events in the queue and send it to another thread...
3
1568
by: Jayman777 | last post by:
Hello, I am using PHP 4.4.1 and am having problems retrieving an object from an array of objects and then calling a method on it. Here are two simple classes that I am using: class Day {
1
4954
by: Bob | last post by:
Hi, Hope you can help me with this one. I'm at my wits end. I'm trying to create an intelligent edit-box like the excellent "Customer" one at the URL: http://munich.schwarz-interactive.de/autocomplete.aspx
18
3942
by: joaotsetsemoita | last post by:
Hello everyone, I'm having troubles assigning an onclick event to a cell. Im trying something like cursorPoint.cells.style.cursor = "hand"; cursorPoint.cells.width = "20"; cursorPoint.cells.onclick = "alert('this is a test');" cursorPoint.cells.alt = "Select the columns"; cursorPoint.cells.innerHTML = " "
4
3344
RMWChaos
by: RMWChaos | last post by:
Darnit all, I expect the code I steal from others to work! =D Below is some code that I got to initiate multiple javascripts on page load (rather than using the "onload=" attribute). According the blog where it was posted, it seems that it works for everyone who posted replies...not a single "this is not working for me" post. The errors I receive are as follows: IE7: expected ";" and then "conditional compilation is turned off" FF &...
7
2227
by: tader | last post by:
Hi, so i done script like that body : function() { for (i = 0; i < all_divs.length; i++) { if (all_divs.title) { addEvent(all_divs, "mouseover", this.onover); addEvent(all_divs, "mouseout", this.onout); all_divs.setAttribute("tooltip", all_divs.title);
53
2976
by: Aaron Gray | last post by:
I jokingly say this is the late entry :) Okay I have read all the event entry comments from John's Resig's AddEvent comepition blog :- http://ejohn.org/projects/flexible-javascript-events/ and put together the following offering for my LGPL'ed library functions :- function addEvent( el, type, fn, cascade) {
0
4284
Dormilich
by: Dormilich | last post by:
Organize your Scripts what you should have: basic Javascript understanding a standard compliant browser additional goodies: Firefox with the Firebug plugin installed
0
9628
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10122
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10061
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8954
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7471
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6722
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4031
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3627
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2860
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.