문제

My question is how to get 1 event or rendered callback when a group of elements are updated in the DOM? If I follow the link in the Blaze wiki https://github.com/avital/meteor-ui-new-rendered-callback this is not what I want. If I follow the second recommendation, I will get as many rendered calls as I have elements. And the parent element will only get 1 rendered callback on page load.

In my case, I'm using the Footable Jquery plugin to format a table. The initial load works fine, but if I change a filter variable in the Collection find, the DOM updates and no rendered is called again since Blaze only calls rendered once. I do not want to put the into another template, because that just means multiple calls to rendered and thus multiple calls to Footable when it only needs one for the entire table.

Any help is appreciated.

<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;
}
도움이 되었습니까?

해결책

The best solution would be to write a custom block helper. Lemme do it for you :)

Implementation

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

Usage

Now, in your templates you can do something like:

<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>

Of course you should customize the behavior of the helper to your own needs.

Reflections

There is also another - more generic - solution that follows the pattern of how markdown helper is implemented here. However, I would not encourage to apply this strategy to your specific usecase.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top