如何正确处理为流星准备的dom [英] how to properly handle dom ready for Meteor

查看:56
本文介绍了如何正确处理为流星准备的dom的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用Iron-Router,这是我第一次尝试Meteor平台的尝试.我遇到了一个问题,其中大多数jquery库未能正确初始化,因为Meteor呈现html的方式$(document).ready()在呈现任何模板之前就已触发.我想知道是否有来自Meteor/iron-router的回调允许我替换jQuery的dom?

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?

此外,如果其中一些元素是由jQuery/javascript定制的,我应该如何(轻松,正确地)处理dom元素的实时更新?

Also, how should I (easily and properly) handle the live update of the dom elements if some of them are customized by jQuery/javascript?

这是我当前正在做的事情,我觉得它很hacky,如果在初始化后更新元素,可能会遇到问题.

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;
      }
    }
  });
}

推荐答案

对于Meteor,您通常想考虑何时准备好模板,而不是何时准备好 dom 准备好了.

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

例如,假设您要使用jQuery DataTables插件将排序添加到由模板创建的表元素中.您将收听模板的呈现事件,并将插件绑定到dom:

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:

JavaScript:

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

现在,无论何时重新渲染模板(例如,如果数据更改),都将调用您的处理程序,并且您可以将jQuery插件再次绑定到dom.

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.

这是一般方法.有关完整的示例(包括用行填充表),请参见 answer .

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

这篇关于如何正确处理为流星准备的dom的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆