允许绑定到ember组件上的任何data

编程入门 行业动态 更新时间:2024-10-27 15:24:06
允许绑定到ember组件上的任何data- *属性(Allow binding to any data-* attribute on an ember component)

我正在设计一个库,我希望允许用户提供他们可能喜欢的任何data属性。

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

我不知道他们可能想要绑定哪些data属性,因此无法将它们添加到attributeBindings数组中。

这有解决方法吗?

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?

最满意答案

使用组件的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); }

看到更新的旋风 。

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.

更多推荐

本文发布于:2023-07-30 01:24:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1321362.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:绑定   组件   ember   data

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!