2014-06-30 38 views
0

我正在用Meteor創建一個應用程序,我有一個菜單按鈕,它是一個顯示和隱藏邊欄的切換按鈕。 (綠色條)流星:DOM元素在Template.rendered回調函數中還不存在

頁面加載完成或用戶登錄後,如果瀏覽器寬度大於768px,我想單擊菜單切換按鈕以顯示它。

目前,我通過反應性地檢查Meteor.user()來實現這一目標,因爲如果用戶登錄並且用戶第一次登錄,則在加載頁面後調用Meteor.user()。

userEnabled =() -> 
    if Meteor.user() 
    console.log 'user Enabled called ' + menuOpen 
    if $(window).width() > 768 
     if menuOpen is false 
     console.log 'reached inside' 
     # Need to use setTimeout before clicking because .show-left element has just been added back to the screen, so we need to wait. I don't like this very much, need to find better method. 
     setTimeout -> 
      $('.show-left').click() 
     , 600 

Deps.autorun() -> 
    userEnabled() 

的問題是,在頁面加載某些原因,userEnabled()有時被稱爲兩倍,因此它的開放和關閉邊欄。另一個問題是不得不使用setTimeout方法來等待菜單切換元素的存在,所以我可以點擊它。沒有setTimeout,元素不會被點擊。

所以2個問題

1)客戶端登錄的回調被調用兩次

2)我必須使用setTimeout的等待元素點擊之前存在。

我該如何解決這個問題?

讓我知道你是否需要我提供更多信息,並非常感謝你的幫助。

回答

1

解決方案(使用Meteor.defer與回調函數):

userEnabled =() -> 
    if Meteor.user() 
    if $(window).width() > 768 
     if !$('.show-left').hasClass 'active' 
     # Need to use setTimeout before clicking because .show-left element has just been added back to the screen, so we need to wait. I don't like this very much, need to find better method. 
     Meteor.defer -> 
      $('.show-left').click() 

Router.map -> 
    @route 'template1', 
    path: '/template1', 
    @route 'addAndSearchPosts', 
    path: '/', 
    onAfterAction: -> 
     userEnabled() 

通知,而不是點擊$之前使用的setTimeout( '顯示左。')按鈕,我用Meteor.defer。 Meteor.defer等待DOM完全更新並且具有所有需要的元素。否則,當嘗試訪問渲染上的DOM元素時,如果沒有這個,他們最終可能無法工作!使用帶回調的Meteor.defer在DOM上使用事件,或者在呈現的回調函數或onAfterAction函數中更新DOM。

相關問題