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

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

问题描述

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

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?

此外,如果 dom 元素中的某些元素是由 jQuery/javascript 自定义的,我应该如何(轻松且正确地)处理它们的实时更新?

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

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

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.

这是一般方法.有关完整示例(包括用行填充表格),请参阅此答案.

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

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

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