bento
bento

Reputation: 5026

meteor infinite loop

I'm attempting to alter the attributes of a Collection to give them an absolute position before rendering. If the item is first in the collection, it's given a top of 0, and a left of 0. Second is given a top of 0, and a left of 20, etc. But when I try to build this logic into my template, it results in an infinite loop. Here's my code:

if (Meteor.is_client) {

  _.extend(Template.movies, {

    movies: function() {
      var movies = Movies.find({}, {sort: {name: 1}});

      var determineLocation = function(){
        console.log('hello');

          var count = 0; 

            movies.forEach(function(movie){
              // do some math
              Movies.update(movie._id, {$set: {left: 10, top: 20}});
              count++; 
            });
          }; 

      determineLocation(); 

      return movies; 
    }
  });
};

I think it's doing this because the Movies.update command triggers the movies function to render again, thus resulting in the infinite loop. How should I get around this? Where is the proper location to put the determineLocation function?

Upvotes: 0

Views: 706

Answers (2)

DrM
DrM

Reputation: 1142

Put your meteor extension inside of the startup Meteor startup function:

Meteor.startup( function(){
if (Meteor.is_client) {

  _.extend(Template.movies, {

    movies: function() {
    var movies = Movies.find({}, {sort: {name: 1}});

    var determineLocation = function(){
    console.log('hello');

    var count = 0; 

    movies.forEach(function(movie){
          // do some math
          Movies.update(movie._id, {$set: {left: 10, top: 20}});
          count++; 
        });
      }; 

      determineLocation(); 

      return movies; 
    }
  });
};

The startups are more or less merged, so no worries.

Upvotes: 1

Tom Coleman
Tom Coleman

Reputation: 3037

You want this code to run a single time when the client first loads? I think a Meteor.startup call is appropriate:

 Meteor.startup(function() {
   // do the updating part
 });

Upvotes: 1

Related Questions