Access HTML after this.render() in Iron Router

霸气de小男生 提交于 2019-12-12 03:19:03

问题


I need to apply some Semantic UI on newly rendered templates, but I have no idea how to get the rendered HTML from the router. Here's my code :

Router.route('/', {
  name: 'home',

  where: 'client',

  action: function () {

    this.render('home');
  },

  onAfterAction: function () {

    console.log( $('#homeSidebar') );

  }

});

Basically, $('#homeSidebar') should return the sidebar element, but it returns nothing as the HTML is not yet available. The only solution, so far, was to change the function like this

  onAfterAction: function () {
    setTimeout(function () {
      $('#homeSidebarToggle').on('click', function () {
        $('#homeSidebar').sidebar('toggle');
      });
    }, 200);    
  }

Which is neither clean nor safe. How can I run a function immediately as soon as the HTML is availble?


回答1:


You should use onRendered callback on the template. Meteor uses template helpers, events and callbacks for manipulating DOM. Iron Router is just for routing)
Your client/view.html:

<template name="home">
  <div id="homeSidebar">

  </div>
</template>

Your client/view.js:

Template.home.onRendered(function () {
  console.log($('#homeSidebar'));
});



回答2:


You can look at tracker.afterFlush to schedule code to run after all invalidated computations have been dealt with.

However your specific example looks like a common case of a jQuery developer coming into Meteor and just applying jQuery patterns directly. Usually in Meteor there's an easier way.

A simpler and better way to attach an event handler to a template is with template events. In your case:

Template.home.events({
  'click #homeSidebarToggle': function(ev){
    $('#homeSidebar').sidebar('toggle');
  }
});


来源:https://stackoverflow.com/questions/31643674/access-html-after-this-render-in-iron-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!