how to properly handle dom ready for Meteor

meteor

Solution

With Meteor you generally want to think about when a template is ready, not when the dom is ready.

For example, let's say you want to use the jQuery DataTables plugin to add sorting to a table element that's created by a template. You would listen to the template's rendered event and bind the plugin to the dom:

HTML:

<template name="data_table">
  <table class="table table-striped" id="tblData">
  </table>
</template>

JavaScript:

Template.data_table.rendered = function () {
  $('#tblData').dataTable();
};

Now anytime the template is re-rendered (for example, if the data changes), your handler will be called and you can bind the jQuery plugin to the dom again.

This is the general approach. For a complete example (that includes populating the table with rows) see this answer.

Problem

I am currently using iron-router and this is my very first attempt to try out the Meteor platform. I has been running into issues where most of the jquery libraries failed to initialized properly because the of the way Meteor renders html, $(document).ready() fires before any templates are rendered. I am wondering is there any callbacks from Meteor/iron-router that allows me to replace the jQuery's dom ready? Also, how should I (easily and properly) handle the live update of the dom elements if some of them are customized by jQuery/javascript? This is what i am currently doing, i feel like it is very hackish and probably would run into issues if the elements got updated after the initialization. ``` var jsInitalized = false; Router.map(function () { this.route('', { path: '/', layoutTemplate: 'default', after: function(){ if(!jsInitalized){ setTimeout(function(){ $(document).ready( function() { $$$(); }); }, 0); jsInitalized = true; } } }); } ```

Original source

Related problems