我正在设计一个库,我希望允许用户提供他们可能喜欢的任何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.
更多推荐
发布评论