Search code examples
javascriptshadowcustom-element

Javascript Adding function to custom elements in the shadow root


I'm writing an app using shadow root, I found my self using shadow.children[i].addEventListener('click', fn); so much, so I tried to create a custom function to shorthand it, so I wrote:

var $shadow = function(shadow, el, fn){
  console.log(shadow);
  console.log(el);
var children = shadow.children;
for (var i = 0; i < children.length; i++) {
    var child = children[i];
    console.log('child '+child.id+', el '+el);
       if (child.id === el) {
         console.log('match'); 
         return shadow.children[i].addEventListener('click', fn);
         break;
      }
  }
}

and calling it from the custom element as;

$shadow(shadow, 'd', alert('yap!'));

the problem is the function executed directly once the element is called, and not waiting to "listen" to a "click" action on the specified element.

any thought how to fix it?


Solution

  • var $shadow = function(shadow, el, fn){
      console.log(shadow);
      console.log(el);
    var children = shadow.children;
        console.log(children.length);
    for (var i = 0; i < children.length; i++) {
        var child = children[i];
        console.log(children[i]);
        console.log('child '+child.id+', el '+el);
           if (child.id === el) {
             console.log('match'); 
               return shadow.children[i].addEventListener('click', function(){
                   console.log(fn);
                   fn();
               });
             break;
          }
      }
    }
    $shadow(shadow, 'd', function(){alert("yap");});
    

    I understand you want to do at this adress..

    [http://jsfiddle.net/p4fcoftL/]
    

    I hope you find the job