2013-10-20 37 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节点。