获取Ember组件的名称

4
如果我调用Ember.inspect(component),我会得到以下响应:
<app@component:my-component::ember1246>

这表明该组件知道自己的名称(my-component)。有没有一种方法只访问那个名称?
2个回答

7

Ember.inspect()调用对象的toString()方法,然后调用一些内部的Ember Metal函数来推导名称。

然而,人们一直在使用一个内部属性来获取名称:

this.__proto__._debugContainerKey

这将输出 component:my-component ,然后你只需要在处拆分。有一个问题将创建一种公开方式来发布对象元信息,我们将来可以使用它:https://github.com/emberjs/ember.js/issues/10742

1
很高兴听到一个公共的方法正在进行中。 - nullnullnull
.__proto__已经过时,请使用Object.getPrototypeOf(this)._debugContainerKey代替。 - Jennie Ji
我真的很想要这个:Ember.Component.reopen({ classNames: ['this-component-name'] }); - sheriffderek
这是一个值得关注的东西:https://www.npmjs.com/package/ember-cli-component-class-name - 默认情况下添加了thing-name-component - sheriffderek

0

这个正则表达式可以解决问题:

//Returns a string with full name of component, like: <ProjectName@component:path/to/component-name::ember793>
let componentName = this.toString ();

//This regex will match the component and capture the latest part of component path.
let regex = componentName.match (/<[a-zA-Z]+@[a-zA-Z]+:(?:[a-z]+[\/])*([-a-z]+)::[a-zA-Z]+[0-9]+>/); 

//The latest element of array is the component name.
console.log (regex[regex.length-1]); //component-name

请查看https://regex101.com/r/rX9bQ7/3以获取有关此操作方式的完整说明。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接