polymer icon indicating copy to clipboard operation
polymer copied to clipboard

importHref() for multiple files

Open abdonrd opened this issue 10 years ago • 4 comments

With the importHref(href, onload, onerror) we can import an HTML document dynamically.

But we only can pass one file. There is an option to import multiple files? If not, what would be the best way?

abdonrd avatar Dec 15 '15 12:12 abdonrd

Depends on what you want to do, want to load them all async and then do onload, iterate each file and onload or what? Some ideas...

Polymer.importHrefs = (files, onload, onerror) =>
  files.forEach((file, i, files) =>
    Polymer.importHref(file, onload, onerror));

Or async with break onerror:

Polymer.importHrefs = (files, onload, onerror, i = 0) =>
  Polymer.importHref(file, (i === files.length - 1) ? onload : Polymer.importHrefs(files, onload, onerror, i + 1), onerror);

I would wrap importHref in Promises though...

birkir avatar Dec 15 '15 14:12 birkir

Promise.all handles this nicely:

function importHref(href) {
  return new Promise((resolve, reject) => {
    Polymer.Base.importHref(href, function(e) {
      resolve(e.target);
    }, reject, true);
  });
}

// Usage
Promise.all([
  importHref('/elements.html'),
  importHref('/elements2.html'),
  importHref('/elements3.html')
]).then(values => { 
  values.forEach(val => console.log(val.import));
}, e => console.error(e));

http://jsbin.com/kazodirula/edit?html,output

Note: I'm using the new 4th arg to async on Polymer.Base.importHref. That will async load the import but isn't in a release yet.

ebidel avatar Dec 15 '15 17:12 ebidel

Thank you to both!

abdonrd avatar Dec 15 '15 21:12 abdonrd

Hi @ebidel ,

I tried your solution to import multiple elements. But facing issue with rest of the element apart from first element in array.

Other elements are giving error "$" undefined for "this.$.*" , whenever accessing inside that Polymer element.

It will be great help if you have any solution for this.

"Uncaught TypeError: Cannot read property 'somefuntion' of undefined"

swapbuk avatar Feb 22 '17 10:02 swapbuk