提问人:shijistar 提问时间:12/5/2016 更新时间:4/17/2017 访问量:1306
如何在 didReceiveAttrs 钩子中获取真正的 attr 值,如果它是一个可变单元格
How to get real attr values in didReceiveAttrs hook, if it's a mutable cell
问:
请参阅下面的示例代码。
鉴于我有一个组件my-text-box
my-text-box.hbs
{{my-text-box value=modelName}}
我想通过钩子观察属性的变化,而不是为了更好的性能。value
didReceiveAttrs
observers
my-text-box.js
didReceiveAttrs: function(args) {
if (args.oldAttrs == null) {
// This is the initial render, but I don't need to anything here.
} else if (args.newAttrs.value != args.oldAttrs.value) {
// supposed `value` was changed from outside, I can do something here...
// BUT, `args.newAttrs.value` is not always the prop value,
// `Ember` would automatically wrap it with `{{mut}}` helper.
// The data structure would be:
// {
// value: value,
// update: function (val) {
// source.setValue(val);
// }
// }
}
}
我想要的是,我不必关心 attr 值是否是单元格,我应该得到一种始终获得真实值的方法。我看到有一个,但它没有暴露给公共 API。我在想的是,也许应该改变两者,并具有直接值而不是那些对象。mutable
HTMLBars hook
ember-htmlbars/hooks/get-value
Ember
newAttrs
oldAttrs
mutable
有人有办法处理这个问题吗?谢谢!
答:
1赞
locks
12/7/2016
#1
我的建议是自己存储以前的值,然后比较:
export default Ember.Component.extend({
_previousAttr: null,
didReceiveAttrs() {
this._super(...arguments);
if (this.get('_previousAttr') !== this.get('attrName')) {
this.set('_previousAttr', this.get('attrName'));
// do your thing
}
}
});
评论
0赞
shijistar
12/9/2016
谢谢你的建议。这对我来说是有道理的,我也这样做。但我必须为我需要观看的所有属性制作一个,这是很多额外的作品。如果 Ember 提取值和值会更好,我可以轻松地比较它们,而无需任何额外费用。希望 Ember 的维护者能看到这一点,并考虑一下。shadow
new
old
0赞
Shreya Shah
4/20/2019
你有什么解决方案吗?我有同样的问题。请帮忙解决我的!
1赞
starshine wang
4/17/2017
#2
根据 RFC #191,不推荐使用 Ember 组件生命周期挂钩参数。
所以最好这样做:
Ember.Component.extend({
didReceiveAttrs() {
let oldAttrs = this.get('_previousAttrs');
let newAttrs = this.get('newAttrs');
if (oldAttrs && oldAttrs !== newAttrs) {
this.map.move({ from: oldAttrs, to: newAttrs });
}
this.set('_previousAttrs', newAttrs);
}
});
或者,也许您可以使用这个ember-diff-attrs插件一段时间。
上一个:为什么这个函数会改变数据?
评论
newAttrs
并且也不是公共 API:XoldAttrs
observers