0

Probably this question has been asked before, I did my "Google homeworks" without results (it's kind of difficult to ask this as a question).

I find myself doing this often with async callbacks:

var wow;
myFunction(function(something) {
    wow = something;
});

Is there a shorthand to assign the value contained in the callback function to a variable, like above?

I can't change the code of the myFunction.

Possible real case scenario (with Angular):

$http.get(url).success(function(res) {
   $scope.data = res;
}
Alberto
  • 399
  • 1
  • 6
  • 19
  • you mean like [here](http://stackoverflow.com/questions/905298/jquery-storing-ajax-response-into-global-variable)? – Philipp M Oct 02 '14 at 10:26

1 Answers1

0

Yes, you can use a "setter" function like this:

function setter(name) {
  return function(result) {
    $scope[name] = result;
  }    
}

and then:

$http.get(url).success(setter("data"));

Note that this won't work with the first example: there's no way to dynamically assign a variable.

georg
  • 211,518
  • 52
  • 313
  • 390
  • This will do. The only other possible way is to use a precompiler like Coffeescript, were you have the `->` function declaration shorthand – Alberto Oct 02 '14 at 10:39