Question

I am fairly new to JavaScript and even newer to Meteor and am a little confused with what I think I know about variable scope and what the reality is. So I have this Meteor events helper:

Template.test.events({
  'click .selector': function (e) {
   e.preventDefault();
   var someArray = [1,2,3,4];
   var someVariable = "jquery slector data";

   console.log(someVariable); //this works as expected

   someArray.each(function(index, el) {
     console.log(someVariable); //not defined?
   })
  }
})

I was under the impression that any variables declared outside my .each function would be available inside of it? However I am getting not defined. Is this a Meteor specific thing or JavaScript in general? Also, how would I make the variables accessible inside the .each function without making them global? I don't think defining my variable inside the .each loop would be ideal because that would mean multiple trips to the DOM.

Thanks.

Was it helpful?

Solution

The problem seems to be that you're trying to use an each() method, which does not exist on Array.prototype. I believe you're looking for Array.prototype.forEach(). Underscore's _.each(array, callback) method would also work, and is more compatible with older browsers.

This should work:

Template.test.events({
  'click .selector': function (e) {
    e.preventDefault();
    var someArray = [1,2,3,4];
    var someVariable = "jquery slector data";

    console.log(someVariable);

    someArray.forEach(function(val, index) {
      console.log(someVariable);
    });
  }
});

Or, for compatibility:

   _.each(someArray, function(val, index) {
     console.log(someVariable);
   })

I believe your confusion stems from using jQuery's $.each() method, which works differently from the native forEach and Underscore's _.each(). For one, jQuery has a different argument order (notice that I switched the order of the arguments in the code). In general, I'd recommend using Underscore for collection-related functions and use jQuery primarily for DOM manipulation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top