views:

489

answers:

5

Hello,

I would like to listen to method calls.

For example, when an element is appended by anything to the document, I would like to be passed that element to act on it, like:

//somewhere

aParent.appendChild(aChild);

//when the former, a function I defined as listener is called with the aChild as argument

Does anybody know how to do that?

+1  A: 

don't know if that's possible with the core functions, but you could always create your own functions, for the actions you want to monitor:


function AppendChild(oParent, oChild) {

   // your stuff on oParent

   // append oChild
   oParent.appendChild(oChild)
}

or, maybe, modify the actual appendChild(), but that would be tricky...

Filini
A: 

I know that the Dojo Toolkit provides this functionality. You can some explanation here - jump to the section that says "Connecting Functions to One Another". If you are interested, you can look at the source of dojo.connect to see what's going on.

Rakesh Pai
+1  A: 

In Firefox you could rewrite Node.prototype.appendChild to call your own function (saving the original appendChild first, then calling it within) to perform additional actions.

Node.prototype._appendChild = Node.prototype.appendChild;
Node.prototype.appendChild = function myFunct(el){....; this._appendChild(el);}

Internet Explorer doesn't implement these interfaces (but there might be a workaround floating around, maybe using .htc..). IE8 will have Element instead of Node.

Zach
A: 

What you're describing is Aspect Oriented programming. In AOP parlance, your "join point" would be element.appendChild(), and your "advice" is the function that you would like to execute (before and/or after) every matching join point executes.

I've been keenly interested in possibilties for JavaScript AOP this for some time, and I just found this Aspect Oriented Programming and javascript, which looks promising without needed to adopt a big old API. -- I'm really glad that you brought this up. I have uses for this, like temporary logging, timing code segments, etc.

Chris Noe
A: 

Multiple browsers handle the DOM in different ways, and unfortunately the way IE handles things is not as powerful as the way Mozilla does. The easiest way to do it is by using a custom function like the one that Filini mentioned.

However you could also wrap the different browsers DOM objects in a facade and use it for all element access. This is a bit more work but you would then be able to handle all the browsers in the same way and be able to add/remove listeners with ease. I'm not sure if it would be anymore useful than the custom functions, but worth a look at.

Rontologist