Meteor 0.8 Blaze 如何更新 Jquery 插件的渲染更改

Meteor 0.8 Blaze how to update rendered changes for Jquery plugins

本文关键字:插件 Jquery 更新 Blaze 何更新 Meteor      更新时间:2023-09-26

我的问题是,当一组元素在DOM中更新时,如何获得1个事件或渲染回调?如果我点击 Blaze 维基中的链接 https://github.com/avital/meteor-ui-new-rendered-callback 这不是我想要的。如果我遵循第二个建议,我将获得与元素一样多的渲染调用。父元素在页面加载时只会获得 1 个渲染的回调。

就我而言,我正在使用Footable Jquery插件来格式化表格。初始加载工作正常,但是如果我更改集合查找中的过滤器变量,DOM 会更新并且不会再次调用渲染,因为 Blaze 只调用渲染一次。我不想将 放入另一个模板中,因为这仅意味着对渲染的多次调用,因此当整个表只需要一个时,对 Footable 进行多次调用。

任何帮助,不胜感激。

<template name="customerData">
  <table class="table">
    {{#each dataRows}}
    <tr>
      <td>{{first_name}}</td>
      <td>{{last_name}}</td>
      <td>{{email}}</td>
     {{#each phones}}
        <td>{{phone}}</td>
     {{/each}}
    </tr>
    {{/each}}
  </table>
</template>
Template.customerData.rendered = function(){
  $(".table").footable();
}
Template.customerData.phones = function(){
    var result = [];
    _.each(this.phoneNumbers, function(element, index, list){
       result.push({ phone: element});
    });
return result;
}

最好的解决方案是编写一个自定义块帮助程序。莱姆为你做:)

实现

UI.registerHelper('footableBody', function () {
  var dependency = new Deps.Dependency(),
      dataSource = this,
      handle, footable;
  return UI.Component.extend({
    render: function () {
      var self = this;
      return UI.Each(function () {
        return dataSource;
      }, UI.block(function () {
        dependency.changed();
        return self.__content;
      }));
    },
    rendered: function () {
      var $node = $(self.firstNode).closest('table');
      handle = Deps.autorun(function () {
        if (!footable) {
          $node.footable();
          footable = $node.data('footable');
        } else {
          footable.redraw();
        }
        dependency.depend();
      });
    },
    destroyed: function () {
      handle && handle.stop();
    },
  });
});

用法

现在,在您的模板中,您可以执行以下操作:

<table class="table">
  <thead>
    ...
  </thead>
  <tbody>
  {{#footableBody dataRows}}
    <tr>
      <td>{{first_name}}</td>
      <td>{{last_name}}</td>
      <td>{{email}}</td>
      <td>{{phone}}</td>
    </tr>
  {{/footableBody}}
  </tbody>
</table>

当然,您应该根据自己的需要自定义帮助程序的行为。

思考

还有另一个更通用的解决方案,它遵循此处如何实现markdown帮助程序的模式。但是,我不鼓励将此策略应用于您的特定用例。