Creating Web Components using JavaScript on the fly

I tried to create web components directly from JavaScript, but I encountered an issue where the public constructor could not be found. Here's a basic example to illustrate the situation:

The HTML Template:

<polymer-element name="wc-foo" constructor="Foo" noscript>
    <template>
       Hello World!
    </template>  
</polymer-element>

HTML index:

<html>
<head>
    <script src="general/scripts/polymer/polymer.min.js"></script>
    <link rel="import" href="...">
</head>

<body>  
</body>

<script>
    console.log (window); // (1)
    console.log (window.Foo); // (2)
    var foo = new Foo (); // (3)
</script>

</html>

Console Results:

(1) When checking the window object, the constructor function for Foo is present: function (){return f(a)} (2) However, accessing window.Foo returns undefined. (3) Consequently, the attempt to instantiate new Foo() results in an error: Uncaught ReferenceError: Foo is not defined.

If anyone can offer insight into what might be causing this issue, I would greatly appreciate it. Thank you.

Answer №1

To ensure that Polymer has completed its setup, it is important to wait for the polymer-ready event to trigger:

document.addEventListener('polymer-ready', function() {
  console.log (window.Bar); // (2)
  var bar = new Bar(); // (3)
  console.log(bar);
});

Check out the demo here: http://jsbin.com/wivukufe/1/edit

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React - assigning a value to an input using JavaScript does not fire the 'onChange' event

In my React application with version 15.4.2, I am facing an issue where updating the value of a text input field using JavaScript does not trigger the associated onChange event listener. Despite the content being correctly updated, the handler is not being ...

A Vue computed property is returning the entire function instead of the expected value

One of my computed properties is set up like this: methods: { url_refresh: function (id) { return `${this.url_base}?start=${Date.now()}` } } However, when I attempt to print the value on mount: mounted() { console.log(this.url_refresh) ...

Once the "Get Route" button is pressed, I want to save my JavaScript variable into a database

I am seeking to automatically extract data from the Google Maps API and store it in my MySQL database. Specifically, I want details such as source address, destination address, distance, and duration for all available routes to be inserted into my database ...

Leveraging the power of context to fetch data from a store in a React component within the Next

I'm having trouble with the title in my React project, and I'm new to React and Nextjs. When trying to fetch data from my dummy chat messages, I encountered this error: × TypeError: undefined is not iterable (cannot read property Symbol(Sy ...

RequireJS is timing out while loading the runtime configuration

I keep encountering a load timeout error with my run-time configuration, specifically with common.js. Although I have set the waitseconds value to 0 for files loaded from common.js, the loadTimeout issue persists for common.js itself. index.html <scr ...

Exploring the power of VueJs through chaining actions and promises

Within my component, I have two actions set to trigger upon mounting. These actions individually fetch data from the backend and require calling mutations. The issue arises when the second mutation is dependent on the result of the first call. It's cr ...

When the FileReader reads the file as readAsArrayBuffer, it ensures that the correct encoding is used

Currently, I am developing a script in JavaScript to read uploaded .csv/.xlsx files and convert the data into an array containing each row. Using FileReader along with SheetJs, I have successfully managed to achieve this by implementing the following code: ...

Error: Attempting to insert or update the "tokens" table violates the foreign key constraint "tokens_userId_fkey" in Sequelize

I am facing an issue that I can't seem to resolve, as I keep encountering an error related to a constraint violation. The tables involved in this problem are Token and User, which are linked through the userId column. The error occurs when I try to cr ...

Switching the cursor to an image when hovering over an element is causing inconsistency in hover events triggering

Currently, I am attempting to implement an effect that changes the cursor to an image when hovering over a text element and reverts back to the normal cursor upon leaving the text element. However, this functionality is not working as expected when using R ...

Creating a CSS animation to repeat at regular intervals of time

Currently, I am animating an SVG element like this: .r1 { transform-box: fill-box; transform-origin: 50% 50%; animation-name: simpleRotation,xRotation; animation-delay: 0s, 2s; animation-duration: 2s; animation-iterat ...

Utilize toggle functionality for page rotation with rxjs in Angular framework

Managing a project that involves a container holding multiple cards across different pages can be overwhelming. To address this, the screen automatically rotates to the next page after a set time interval or when the user presses the space bar. To enhance ...

Angular: display many components with a click event

I'm trying to avoid rendering a new component or navigating to a different route, that's not what I want to do. Using a single variable with *ngIf to control component rendering isn't feasible because I can't predict how many variables ...

What could be causing my Wikipedia opensearch AJAX request to not return successfully?

I've been attempting various methods to no avail when trying to execute the success block. The ajax request keeps returning an error despite having the correct URL. My current error message reads "undefined". Any suggestions on alternative approaches ...

The event listener activates multiple times on HTML pages that are dynamically loaded with AJAX

Javascript utility function: // This event listener is set using the on method to account for dynamic HTML $(document).on('click', '#next_campaign', function() { console.log('hello'); }); Website layout: <script src=&q ...

Unable to execute JavaScript function by clicking

I've tried everything, but I can't seem to change the button text when selecting an item in the "Requirements" dropdown. You can view the issue on this site. Located at the bottom of the page is the "Requirements" dropdown. Each item has an oncl ...

The input box refuses to accept any typed characters

I encountered a strange issue where the input box in the HTML was not allowing me to type anything. const para = document.createElement('p') const innerCard = document.getElementsByClassName('attach') for(let i = 0; i < innerCard.l ...

Transferring application configurations across modules

Questioning my current approach, I am developing a model & collection package (which exposes mongodb results as a model) and aiming for a modular structure. However, within the models, there are hardcoded settings like host, port, password, etc., which ...

What is the best way to design a navigation bar for a one-page application using Vue?

Currently, I am developing a Vuejs single-page application and I'm exploring ways to implement a navbar that can toggle the visibility of different sections within the app upon clicking. While I have successfully designed the navbar layout, I am encou ...

issue with horizontal scrolling in react menu component

**Hi there, I'm encountering an issue with react-horizontal-scrolling-menu. When scrolling, it moves to the right excessively and causes other elements to disappear. Additionally, adding overflowX: 'scroll' to the BOX doesn't activate t ...

Using JavaScript to control the state of a button: enable or

In the process of creating a basic HTML application to collect customer information and store it in a database, I have encountered a specific user interface challenge. Once the user logs into their profile, they should see three buttons. Button 1 = Print ...