rball
rball

Reputation: 6955

Can I use Javascript Closures here instead of a global variable?

Current setup:

var placeId;
function selectPlace(place) {
    $('#selectPlace').html('Selected Place: <b>' + place.Name + '</b>');
    $('#map').hide(400);
    placeId = place.Id;
}

$(document).ready(function()
{
    $('#postMessage').click(function() {
        alert("PlaceId: " + placeId);
    });
});

Can/should I be using closures?

Upvotes: 0

Views: 948

Answers (2)

pottedmeat
pottedmeat

Reputation: 3421

Based on your comments, it seems like what you're looking for is this:

function selectPlace(place) {
  if(!place){
    return selectPlace.placeId;
  }else{
    $('#selectPlace').html('Selected Place: <b>' + place.Name + '</b>');
    $('#map').hide(400);
    selectPlace.placeId = place.Id;
  }
}

$(document).ready(function(){
  $('#postMessage').click(function() {
    alert("PlaceId: " + selectPlace());
  });
});

This isn't using a closure, it just stores the last assigned ID on the function object. Then you'd return the value if they don't use the function as a setter. If you wanted to use a closure to do the same thing, it would look a lot like the example above:

(function(){
  var placeId;

  window.selectPlace = function(place) {
    if(!place){
      return placeId;
    }else{
      $('#selectPlace').html('Selected Place: <b>' + place.Name + '</b>');
      $('#map').hide(400);
      placeId = place.Id;
    }
  }
})();

By the way, the easiest way to spot a closure is if a function has variables in it that haven't been declared with var inside of the current function, but have been in some other function it sits inside. As you can see above, the variable placeId isn't declared inside of the selectPlace function, meaning that the selectPlace function is a closure that uses the placeId variable.

Upvotes: 3

olliej
olliej

Reputation: 36793

It seems a reasonable thing to do, based on the context, you can easily do it by substituting your code with a function expression a la:

 (function(){
     var placeId;
     // It looks like you want selectPlace to be a global function?
     // hence i'm using assignment of a function expression here
     selectPlace = function (place) { 
         $('#selectPlace').html('Selected Place: <b>' + place.Name + '</b>');
         $('#map').hide(400);
         placeId = place.Id;
     }

     $(document).ready(function()
     {
         $('#postMessage').click(function() {
             alert("PlaceId: " + placeId);
         });
     });
 })();

Upvotes: 6

Related Questions