簡體   English   中英

允許綁定到 ember 組件上的任何 data-* 屬性

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

我正在設計一個庫,我希望允許用戶提供他們可能喜歡的任何data屬性。

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

我不知道他們可能想綁定到哪些data屬性,因此無法將它們添加到attributeBindings數組中。

有解決方法嗎?

使用組件的didReceiveAtts鈎子:

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);
}

看看樣本旋轉

棄用后更新:

由於didReceiveAttrs函數的參數已被棄用,因此您需要按以下方式更改代碼:

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

更新的旋轉

我猜在 v3.10 之后,您可以使用尖括號調用(如果需要進一步使用...attributes傳遞), 而無需任何技巧即可完成此操作 所以在我最簡單的情況下,它就像

<MyComponent data-aaa="bbb"/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM