对于Ember 2.0,有一个弃用用于修改组件的didInsertElement
挂钩中的属性。以下方案在尝试集成其他第三方库时会出现问题,在本例中为d3。
我有一个包含d3可视化的ember组件,其格式为tagName: svg
。有两个属性从父级传递到此组件width
和height
。在d3组件中有这两个属性的观察者可以更新可视化,使其响应窗口大小的变化。
问题出现在父组件中。我目前正在绑定window
resize事件,运行Ember.run
以及一个设置组件中windowSize
属性的回调。我有两个依赖于windowSize
的计算属性,宽度和高度是根据DOM的宽度和高度计算的(由于bootstrap中的列,它们是动态的)。因此,计算出的属性如下所示:
halfWidth: Ember.computed('windowSize', function() {
return $(this.get('halfSelector')).first().width();
})
但是,当将计算属性作为{{d3-component width=halfWidth}}
传递给d3组件时,没有默认值。只有在触发窗口上的resize事件时才会计算此计算属性。如果我调整窗口大小,d3组件将使用新宽度正确更新。
didInsertElement() {
$(window).on('resize', () => {
Ember.run(() => {
this.set('windowSize', $(window).width());
});
});
// In order have the computed properties to have defaults, one could do
// $(window).trigger('resize')
// However this line is responsible for raising the deprecation notice.
}
如何将计算属性赋予默认值,该值取决于组件插入DOM后DOM节点的宽度?
答案 0 :(得分:0)
为了摆脱弃用,我将didInsertElement的定义更改为以下内容:
didInsertElement() {
let onWindowResize = () => {
this.set('windowSize', $(window).width());
};
$(window).on('resize', () => { Ember.run(onWindowResize); });
Ember.run.scheduleOnce('afterRender', onWindowResize);
}
我从https://github.com/emberjs/ember.js/issues/11493获得灵感。该问题也被引用为Forcing layout calculations to use in further positioning
。为了避免在didInsertElement
挂钩中弃用设置属性,可以使用afterRender
队列来安排更改。