2016-11-02 64 views
3

我想在我的Ember應用程序中加載所有內容(例如圖像)時執行JavaScript。是否有類似'onload`的Ember事件

我已經嘗試使用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); 
     }); 
    }, 
}); 

任何解決方案或此替代方法嗎?

+0

看看[這個](http://stackoverflow.com/questions/10385578/is-there-a-way-to-get-a-callback-when-ember-js-has-finished-loading -everything) –

+0

你想通過添加className'homePage'來實現什麼?你能否在你的模板中解決這個問題? –

+0

我想在加載頁面時啓動css動畫 –

回答

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); 
    }, 
}); 

willDestroyElement鉤已包括在內,從window顯示load事件偵聽器的正確拆卸和拆除。

我創建了一個Ember Twiddle example來演示這個給你。

+1

在每次重新渲染時會調用'didRender',這可能會發生很多次,並且您可能不希望每次渲染都發生時分配一個加載偵聽器。您只想在組件第一次插入到DOM時執行此操作,即在'didInsertElement'中。您可能還想在'willDestroyElement'中將其刪除' – nem035

+1

@ nem035感謝您的良好代碼審查 - 更新了這些重構。 – jacefarm

相關問題