Shivam Sinha
Shivam Sinha

Reputation: 5150

Ember customize id attribute of component

Hi is there a way to customize the id of a component (i know it can be done for views ...but views have be deprecated since ember 1.13):

E.g. the following worked for the view:

export default Ember.View.extend({
    classNames: ['music-js', 'vjs-default-skin', 'center-x','center-block'],
    attributeBindings: ['id'],
    id: 'musicOne',

However when I attempt to use id binding for the component i get the exception in the console logs:

export default Ember.Component.extend({
    classNames: ['music-js', 'vjs-default-skin', 'center-x','center-block'],
    attributeBindings: ['id'],
    id: 'musicOne',

Uncaught TypeError: The element or ID supplied is not valid.

Upvotes: 12

Views: 9504

Answers (2)

rmcsharry
rmcsharry

Reputation: 5552

I think the reason for NOT being able to do this is that the component is automatically assigned an ID by the Ember framework itself. You can see that if you inspect the HTML when you run your app:

<div id="ember428" class="ember-view">

But you can get a handle on that auto-generated ID and pass that to the JQuery plugin, instead of creating your own ID as per Mikko's answer.

See this to learn how to do that.

I think this is the preferred way, since components should be 'isolated' from external dependencies. By having to pass in the ID from the template defeats that (as per Mikko's suggestion) - since any consumer of a component would have to know what ID to pass in for the component to work.

However, Mikko has now edited his answer, so setting your own ID inside the component, also satisfies the 'isolation' requirement (ie. using elementID: 'the-id')

Upvotes: 2

Mikko Paderes
Mikko Paderes

Reputation: 840

2 ways:

In the component itself:

export default Ember.Component.extend({
  elementId: 'the-id'
});

Or specifying it in the component call itself:

{{my-component id="the-id"}}

Upvotes: 25

Related Questions