简体   繁体   English

从DOM元素获取一个Ember组件

[英]Get an Ember Component from the DOM Element

I have an Ember Component as So... 我有一个余烬组件...

export default Ember.Component.extend({
    didInsertElement: function() {
        this.$().sortable({
            connectWith: '.droppable-box',
            receive: (e, ui) => {

            }
        });
    },
    tagName: 'ul',
    classNames: ['droppable-box', 'list-unstyled']
});

The elements inside the sortable components are also components... 可排序组件内部的元素也是组件...

export default Ember.Component.extend({
    tagName: 'li'
});

The receive event is fired whenever a element is moved into a sortable component. 每当将元素移动到可排序组件中时,都会触发receive事件。

I am given the DOM element, but I want to get access to the instance of that Ember Component. 我得到了DOM元素,但我想访问该Ember Component的实例。 Any ideas? 有任何想法吗?

This is not the cleanest solution, but it should work. 这不是最干净的解决方案,但它应该可以工作。

In your child component add the following lifecycle hooks: 在您的子组件中,添加以下生命周期挂钩:

//components/child-component.js
...
registerRow: Ember.on('willInsertElement', function () {
  this.attrs.onRegister(this.get('elementId'), this);
}),

unregisterRow: Ember.on('willDestroyElement', function () {
  this.attrs.onUnregister(this.get('elementId'));
}),

In the parent template, pass the action handlers to all child components: 在父模板中,将操作处理程序传递给所有子组件:

//components/parent-component.hbs
{{#each children as |child|}}
  {{child-component onRegister=(action "registerChild") onUnregister=(action "unregisterChild")}}
{{/each}}

In the parent component, create a dictionary to store child components indexed by their elementId: 在父组件中,创建一个字典来存储按其elementId索引的子组件:

//components/parent-component.js
...
children: null,

initChildren: Ember.on('init', function () {
  this.set('children', {});
}),

actions: {
  registerChild(elementId, child) {
    this.children[elementId] = child;
  },

  unregisterChild(elementId) {
    delete this.children[elementId];
  }
}

Now, to access components from your jQuery callback, do: 现在,要从jQuery回调访问组件,请执行以下操作:

// Presuming ui is a DOM element
receive: (e, ui) => {
    let component = this.children[ui.id];
}

There is a cleaner way to do this, but uses Ember private API. 有一种更干净的方法可以执行此操作,但是使用Ember专用API。

The root element of the Ember.Component is assigned an id. Ember.Component的根元素分配有一个ID。 You can use this id to lookup the component. 您可以使用此ID查找组件。

// Ember 1.x
Ember.View.views[id]

// Ember 2.x
container.lookup('-view-registry:main')[id]

I do believe there is an instance of the container attached to components. 我确实相信有一个容器实例附加到组件上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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