Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delegate() in PrototypeJS

I am used to jQuery, which has a delegate() method. So let's say I have HTML like this:

<div id="covers">
   <a href="#"><img ... /></a>
   <a href="#"><img ... /></a>
   <a href="#"><img ... /></a>
   <a href="#"><img ... /></a>
   <a href="#"><img ... /></a>
   <a href="#"><img ... /></a>
   ...lots anchors here...
</div>

In jQuery, I can bind events to the parent div and not attach individual handlers to new, dynamically added anchors using delegate() like so:

$('#covers').delegate('a', 'click', function(){
   /// stuff I want to do
   var clickedAnchor = $(this);
});

What would the equivalent code be in Prototype?

like image 857
artlung Avatar asked Dec 12 '25 22:12

artlung


1 Answers

Prototype's philosophy is that you do it more like in pure javaScript only with added cross-browser abstractions (plus releasing once a year, plus polluting native prototypes).

So there's no delegate in Prototype. You can use Event#findElement though.

$('covers').observe('click', function (event) {
  var link = event.findElement('a');

  if (link) {
      // ...
  }
});

Edit: There is delegate in Prototype: http://api.prototypejs.org/dom/Event/on/!

$('covers').on('click', 'a', function (event, element) {
   // ...
});
like image 91
katspaugh Avatar answered Dec 14 '25 11:12

katspaugh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!