简体   繁体   中英

Ember - Dynamically create a component

I'm working on a module which needs to register components with Ember, Angular, React etc. depending on what is loaded into the page.

With React I can just do

if (window.React) {
  React.createClass(...

But how can I do the same with Ember? I'm looking for something like:

if (window.Ember) {
  Ember.registerComponent('my-component-name', Ember.Component.extend({
    ...
  }));
}

Is this possible? Bearing in mind I don't have access to the Ember App on the page .

This is a good question. To break it down a bit, we want to dynamically:

  1. Create a subclass of Ember.Component .
  2. Compile that Component's template.
  3. Register that Component in the app's global namespace.

The answer to 1. is already in your question ( Ember.Component.extend ). 2. has been answered elsewhere: here and here , for instance.

Off the top of my head, I'm not sure of an airtight answer for 3-- I'd recommend looking at using register on Ember's Dependency Injection container, or searching SO specifically for that goal.


Be forewarned that this isn't really on the Ember "happy path"-- for performance reasons, Ember (and Glimmer) are mostly focused on precompiled templates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM