Jquery Pass More Parameters into Callback

jQuery pass more parameters into callback

The solution is the binding of variables through closure.


As a more basic example, here is an example function that receives and calls a callback function, as well as an example callback function:

function callbackReceiver(callback) {
callback("Hello World");
}

function callback(value1, value2) {
console.log(value1, value2);
}

This calls the callback and supplies a single argument. Now you want to supply an additional argument, so you wrap the callback in closure.

callbackReceiver(callback);     // "Hello World", undefined
callbackReceiver(function(value) {
callback(value, "Foo Bar"); // "Hello World", "Foo Bar"
});

Or, more simply using ES6 Arrow Functions:

callbackReceiver(value => callback(value, "Foo Bar")); // "Hello World", "Foo Bar"

As for your specific example, I haven't used the .post function in jQuery, but a quick scan of the documentation suggests the call back should be a function pointer with the following signature:

function callBack(data, textStatus, jqXHR) {};

Therefore I think the solution is as follows:

var doSomething = function(extraStuff) {
return function(data, textStatus, jqXHR) {
// do something with extraStuff
};
};

var clicked = function() {
var extraStuff = {
myParam1: 'foo',
myParam2: 'bar'
}; // an object / whatever extra params you wish to pass.

$.post("someurl.php", someData, doSomething(extraStuff), "json");
};

What is happening?

In the last line, doSomething(extraStuff) is invoked and the result of that invocation is a function pointer.

Because extraStuff is passed as an argument to doSomething it is within scope of the doSomething function.

When extraStuff is referenced in the returned anonymous inner function of doSomething it is bound by closure to the outer function's extraStuff argument. This is true even after doSomething has returned.

I haven't tested the above, but I've written very similar code in the last 24 hours and it works as I've described.

You can of course pass multiple variables instead of a single 'extraStuff' object depending on your personal preference/coding standards.

Pass an extra argument to a callback function

Just create a function(magic) {} as a wrapper callback:

callWithMagic(function(magic) {
return processMagic(magic, 42);
});

Or using ECMAScript 6: arrow functions:

callWithMagic(magic => processMagic(magic, 42));

Passing a callback function with included parameters?

change your callback to an anonymous function:

// Set the callback function to run on success
var callback = function () {
showGradesBox(grading_company);
};

This allows you to pass parameters to the inner function.

Edit: to allow for the ajax response:

// Set the callback function to run on success
var callback = function (response) {
showGradesBox(grading_company, response);
};

Passing parameters to a callback

You can bind dropdown to callback function:

$("#refine_mp_type").change(function(){
var mp_type = $(this).val();
var country_id = $('#refine_country').val();
var dropdown = $('#refine_grade').find('select');
getMPTypeGrades(country_id, mp_type, populateGradesDropdown.bind(null, dropdown));
});

Then

populateGradesDropdown(dropdown, data){
//populate the dropdown with the returned data
}

Pass arguments to a callback function in jquery click event

The clean way to handle this is to return a function:

function printNumber(number) {
return function(e) {
console.log(number);
};
}

And then use:

$(".number").click(printNumber(number));

jQuery.each() - passing extra argument to the callback parameter

Try binding the context, using bind (warning not IE8 compatible):

$.each(elem, setCount.bind(this))

This makes the this-context inside each setCount-call, pointing to this from the event handler.

Pass extra parameters to jquery.Deferred callback

In order to pass something to .done callback you need to pass it in .resolve, for example

dfd.done( function(selector) {
console.log( selector );
});
dfd.resolve( selector );

but in your case dfd is a $.ajax object and .resolve is called internally, so you have no control over it. Therefore the only way to do that is to use anonymous function and closure.

By the way: there is nothing unclean about this solution.

How do I pass custom parameters into the callback method of a jQuery AJAX method?

I tested the code suggested in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function just to see if I could access the value outside of the Promise, and it failed as it has always been doing...

var xyz = "please";

function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}

async function asyncCall() {
console.log('calling');
const result = await resolveAfter2Seconds();
xyz = result;
//console.log(result);
// expected output: "resolved"
}

asyncCall();

console.log(xyz);

It returns 'please'.

Either I'm not understanding the solutions provided, or what I'm trying to achieve is not being understood. I'm happy to accept that this is a "me" problem.

The answer would've been simple if it was just a case of setting async to false in the ajax query, but that's deprecated.

The answer is: I give up, but only because it's probably unwise for multiple methods to rely on multiple ajax calls for their logic.

So instead, I'm going to import the records from the json file into an array so I'll always have access to the data without this headache.

Pass additional parameters to jQuery each() callback

You should be able to create a reference to your survey before you iterate over the questions.

function Survey() {
this.questions = new Array();
var survey = this;
$('.question').each(function(i) {
survey.questions.push(new Question(this));
});
}

function Question(element) {
this.element = $(element);
}

var survey = new Survey();

$.each(survey.questions, function() {
$("ul").append("<li>" + this.element.text() + "</li>");
});

Working example on jsfiddle



Related Topics



Leave a reply



Submit