Akhar
Akhar

Reputation: 108

Run code on client after helpers

How do I initialize a jQuery plugin after helper deliver data for template?

I have the following template:

<div class="scrollyeah">
  {{#each projects}}
    {{!-- some data --}}
  {{/each}}
</div>

and client-side code:

Template.templateName.onRendered(function() {
  $(document).ready(function() {
    $('.scrollyeah').scrollyeah();
  });        
});

Time to time it works, but sometime I have errors like that:

Exception from Tracker recompute function: Error: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.

Update

Solution is use autorun and wait for subscribtions ready:

Template.templateName.onRendered(function() {
  this.autorun(function() {
    if (Meteor.subscribe('projects').ready()) {
      $('.scrollyeah').scrollyeah();
    }
  });        
});

Upvotes: 0

Views: 246

Answers (2)

MasterAM
MasterAM

Reputation: 16478

The initial call is done after the first time the helpers are run.

It is not likely that those errors can be fixed without messing with Blaze internals.

The jQuery plugin changes the DOM structure, so when a re-computation is done (possibly due to a change in the cursor that is returned by projects), Blaze does not find the structure that is expected (e.g, a project is to be removed and the related node is no longer a child of the .scrollyeah div).

It is also possible that the helpers are re-run after the template has rendered in case the subscription did not have all of the data. You can take care of this by only rendering the list once the subscription is ready, but this won't solve your issue.

Be careful when dealing with jQuery plugins that change the DOM in such a way.

BTW, wrapping it with $(document).ready is probably redundant.

Upvotes: 1

Nicolas Charpentier
Nicolas Charpentier

Reputation: 1118

I think you should put this inside autorun. Use template.autorun instead of Tracker.autorun because template.autorun is stopped when the template is destroyed. See Meteor Docs.

Run a function now and rerun it later whenever its dependencies change. Returns a Computation object that can be used to stop or observe the rerunning.

Template.templateName.onRendered(function() {
  this.autorun(function() {
    $(document).ready(function() {
      $('.scrollyeah').scrollyeah();
    });
  });
});

Upvotes: 0

Related Questions