Blackbam
Blackbam

Reputation: 19386

Pass local variable to lambda function with arguments?

Have a look at the following examples:

var data = "abc";   

$.post(ajaxurl,data,function(results) {
    console.log(data);
    console.log(results)
} ,'JSON');

data = "ghi";

Result:

data: "ghi"

results: "results"

Passing data:

var data = "abc";   

$.post(ajaxurl,data,function(results) {
    console.log(data);
    console.log(results)
} (data) ,'JSON');

data = "ghi";

Result:

data: "abc"

results: "abc"

However what I want to achieve is to pass the local variable data but recieve the passed variables from the callback anyway.

Desired output:

data: "abc"

results: "results"

In PHP this would be something like:

function abc($result) use ($data) {
    //...
}

How can I achieve this behaviour?

Edit - Clarification: I want to pass the current state of a local variable to an aynchronous request callback with arguments.

Upvotes: 1

Views: 2941

Answers (2)

charlietfl
charlietfl

Reputation: 171689

You can use an IIFE to create a closure around the whole request. Assumes data is a primitive value. If it is array or object you either need to copy it or use promise callback to change it since arrays and objects are passed by reference not value

var data = "abc"; 

(function(data){    

    $.post(ajaxurl,data,function(results) {
     console.log(data); // abc
     console.log(results)
     } ,'JSON');

})(data);

data = "ghi";

Upvotes: 2

Jared Smith
Jared Smith

Reputation: 21965

Based on the conversation in the comments, you want this:

var data = "data";
$.post(ajaxurl,data,(function(data) { // shadows outer data
  return function(results) {
    console.log(data); // logs "data" not "foo"
    console.log(results); // logs the AJAX results
  };
})(data) ,'JSON');
data = "foo";

This will log "data" to the console rather than "foo" even though the async op completes later.

Upvotes: 3

Related Questions