2013-10-20 55 views
1

我想將一個類添加到是我所有DOM樹的父元素的DOM元素。 我嘗試不同的方法:流星 - 在模板加載DOM類元素上添加類

//this one doesn't work at all. DOM is not loaded 
Template.home.created = function() { 
    Meteor.startup(function() { 
     $("#wrapper").addClass('app'); 
    }); 
} 

//this one only works if you do a page load, not if you render the template through a link (using router) 
Template.home.created = function() { 
    Meteor.startup(function() { 
     $(document).ready(function() { 
      $("#wrapper").addClass('app'); 
     }); 
    }); 
} 

//also does not work if I click on a link 
Template.home.created = function() { 
    $(document).ready(function() { 
     $("#wrapper").addClass('app'); 
    }); 
} 

//does not work at all (I really expected this one to work by clicking on a link (using router)) 
Template.home.created = function() { 
    $("#wrapper").addClass('app'); 
    }); 
} 

我試圖做的得不能再簡單:添加一個類,所以我可以據此風格我的包裝到每個模板。任何建議如何做到這一點將不勝感激。

回答

5

模板創建的方法在模板實例初始化但不等待DOM準備好進行操作時調用。

使用(每次爲第一負載一次,在模板內的標記的變化)的模板渲染方法,當DOM已經由模板被渲染後調用

像這樣的東西應該工作(避風港」噸測試):

Template.home.rendered = function(){ 
    var element = $("#wrapper"); 
    if(!element.hasClass("app")){ 
     element.addClass("app"); 
    } 
} 
+0

這個作品,謝謝。我不想使用home.rendered,因爲它會在我重新呈現模板時運行此代碼,而不僅僅是第一次。無論如何,看起來他們正在改變這個版本的下一個版本,所以我不認爲這是一個大問題。 謝謝! –

+0

@LucasLobosque沒問題,我很高興聽到它的工作。我不知道他們計劃在下一個版本中改變'呈現'的行爲。我非常希望能夠看到它的推出,因爲它會照顧我的項目中幾個低優先級的bug,這些bug一直在困擾着我。 –

2

嘗試使用Template.home.rendered而不是Template.home.created。請勿在其中使用Meteor.startup$(document).ready

http://docs.meteor.com/#template_rendered

Template.home.created創建模板對象時被調用,但一切都沒有在這一點上被渲染成DOM節點。