Correct stopping the autostart function () when destroying a template

I have a template containing a chart displayed using MorrisJS. The chart needs to be updated when the session variable changes currentData, so I made it a reactive data source with:

Template.chart.rendered = function() {

    var template = this;

    Deps.autorun(function(c) {

        // Stop if the template is removed from the dom
        // Q: Is this really right?
        if(template.__component__.dom.parentNode() === null) {
            c.stop();
            return;
        }

        var results = Session.get('currentData');

        // ... render a chart with `results` as the data

        Morris.Bar({element: template.$(".chart-container"), data: results, ...});

    });

};

Notice how I do a pretty terrible check when to stop autostart above. This was necessary because without it, when I go from the page using the template (I use iron-router) to another page and back, I get warnings in the log, for example, "I can’t choose in remote DomRange." I am sure this is happening because the template instance has been deleted, but autostart is still running.

, - . () , () , DOM?

created destroyed, , .

+4
2

Tracker.autorun , , stop onDestroyed.

Template.chart.onRendered(function(){
  this.computation = Tracker.autorun(function(){...});
});

Template.chart.onDestroyed(function(){
  this.computation.stop();
});

EDIT 29-09-2014

Meteor (0,9) autorun, , : , .

Template.chart.onRendered(function(){
  this.autorun(function(){...});
});
+6

Template.chart.onRendered(function(){
  this.autorun(function(computation){
    ...
    computation.stop();
  });
});

, DOM, . Meteor :

.

+1

Source: https://habr.com/ru/post/1545299/


All Articles