views:

748

answers:

3

I'm trying to add a listener to DOM change events. I was hoping something as simple as 'dom:loaded' was baked into Prototype. I'm not sure of the 'Prototype-way' to handle this.

EDIT: I cannot control every case in which the DOM may be altered, so I can't get away with firing a custom event on every DOM change.

+2  A: 

I would recommend that you take a look at the documentation for Event.observe from the prototype documentation.

As an example using dom:loaded

document.observe("dom:loaded", function() {  
       // Some Javascript Code
                  });

And an example of Event.observe

$('step_anchor_' + i).observe('click', function(a, b){
     return function(){pm.loadData(a, b, true)};
      }(profile.steps[i].action, profile.steps[i].dao_id)
             );

I should point out that obviously document also has an observe function that is specifically designed to listen for events on the entire document such as dom:loaded.

Noah Goodrich
I understand this -- I'm interested in what event I need to observe in order to detect that the DOM has changed. I was hoping for some sort of 'dom:changed' event like the DOM level 2 DOMEvent MutationEvent.MODIFICATION.
A: 

There is no standard handler to watch this. However, you can fire custom events in Prototype. Combined with Function.wrap, you should be able to do exactly what you need.

Essentially, you take any function that can modify the DOM, such as Element.insert(), and wrap it with a function that fires your change event:

Element.prototype.insert = Element.prototype.insert.wrap(
function(original) {
    var ret = original.call(this, $A(arguments).slice(1));
    document.fire('dom:changed');
}.bind(this)
);

Now, whenever you call Element.insert, it will fire 'dom:changed', which can be watched with Event.observe().

I can't guarantee what I just wrote is 100% perfect nor 100% versatile, but it should get you started.

dave mankoff
I think he means the Prototype javascript library, not the OO technique.
Diodeus
Hmm..that's unfortunate. I don't have access to everything that could potentially alter the DOM.
+1  A: 

$(element).observe('click', function(event) { someFunction(event); } ); //someFunction will be called on the click event. This can be changed to any other event.

http://prototypejs.org/api

Go to Element to see more.

geowa4