jax
jax

Reputation: 38583

Allow binding to any data-* attribute on an ember component

I am designing a library whereby I would like to allow the user to supply any data attributes they might like.

{{my-component data-type='hello' data-name='world'}}

I don't know ahead of time which data attributes they might like to bind to so can't add them to the attributeBindings array.

Is there a workaround for this?

Upvotes: 1

Views: 731

Answers (2)

Andrey Stukalin
Andrey Stukalin

Reputation: 5929

I guess after v3.10 you can do this without any hacks with the angle bracket invocation (and if required pass further using the ...attributes). So in my simplest case it was as simple as

<MyComponent data-aaa="bbb"/>

Upvotes: 0

ykaragol
ykaragol

Reputation: 6221

Use the didReceiveAtts hook of your component:

didReceiveAttrs(params){
  let newAttrs = params.newAttrs;
  let attributeBindings = Ember.A();
  Object.keys(newAttrs).forEach((attr)=>{
    if(attr.indexOf('data-')>= 0){
      attributeBindings.pushObject(attr);
    }
  });
  this.set('attributeBindings', attributeBindings);
}

Look that Sample twiddle

Updated, after deprecation:

Since arguments of didReceiveAttrs function are deprecated, you need to change the code as the following:

didReceiveAttrs(){
  let attributeBindings = Ember.A();
  Object.keys(this).forEach((attr)=>{
    if(attr.indexOf('data-')>= 0){
        attributeBindings.pushObject(attr);
    } 
  });
  this.set('attributeBindings', attributeBindings);
}

See updated twiddle.

Upvotes: 2

Related Questions