有没有类似于 `onload` 的 Ember 事件?

3

我希望在我的Ember应用程序中所有内容(例如图片)都加载完成后执行JavaScript。

我已经尝试使用didInsertElement()didRender()钩子,但看起来它们不会等待背景图像加载。

这是我的组件代码片段:

export default Ember.Component.extend({
    didInsertElement() {
      this._super(...arguments);
      Ember.run.scheduleOnce('afterRender', this, function() {
        var home =$('#main-outlet')[0];
        home.className += " homePage";
        startTimer(5);
      });
    },
});

有没有解决方案或替代方法?针对这个问题,您是否有任何建议?

请查看这个链接 - Kevin Kloet
通过添加homePage类名,你想要实现什么目标?你不能在模板中解决这个问题吗? - Jacob van Lingen
当页面加载时,我想要启动CSS动画。 - Aman Jagga
1个回答

2

Ember没有与onload等效的事件。

然而,关于另一种方法,您可以利用Ember对jQuery的别名,结合组件中的didInsertElement钩子,实现您想要的执行顺序。尝试这个:

export default Ember.Component.extend({
  didInsertElement() {
    Ember.$(window).on('load', this.executeCssAnimations);
  },

  executeCssAnimations() {
    // your CSS and animation logic would go here
    Ember.$('.big-background')
         .text('NOW READY FOR CSS and ANIMATION UPDATES.')
         .css('color', 'yellow');
  },

  willDestroyElement(...args) {
    this._super(...args);
    Ember.$(window).off('load', 'window', this.executeCssAnimations);
  },
});

为了展示如何正确清除和移除从window加载的事件监听器,willDestroyElement钩子也已被包含。

我创建了一个Ember Twiddle示例来为您演示此操作。


1
didRender gets called on every re-render, which can happen a lot of times and you probably don't want to assign a load listener every time a render happens. You only want to do it when the component is first inserted into the DOM, i.e. in didInsertElement. You might also want to remove it in willDestroyElement - nem035
1
@nem035 感谢您的良好代码审查 - 已经更新了这些重构。 - jacefarm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接