Create a Custom Callback in JavaScript

Create a custom callback in JavaScript

Actually, your code will pretty much work as is, just declare your callback as an argument and you can call it directly using the argument name.

The basics

function doSomething(callback) {
// ...

// Call the callback
callback('stuff', 'goes', 'here');
}

function foo(a, b, c) {
// I'm the callback
alert(a + " " + b + " " + c);
}

doSomething(foo);

That will call doSomething, which will call foo, which will alert "stuff goes here".

Note that it's very important to pass the function reference (foo), rather than calling the function and passing its result (foo()). In your question, you do it properly, but it's just worth pointing out because it's a common error.

More advanced stuff

Sometimes you want to call the callback so it sees a specific value for this. You can easily do that with the JavaScript call function:

function Thing(name) {
this.name = name;
}
Thing.prototype.doSomething = function(callback) {
// Call our callback, but using our own instance as the context
callback.call(this);
}

function foo() {
alert(this.name);
}

var t = new Thing('Joe');
t.doSomething(foo); // Alerts "Joe" via `foo`

You can also pass arguments:

function Thing(name) {
this.name = name;
}
Thing.prototype.doSomething = function(callback, salutation) {
// Call our callback, but using our own instance as the context
callback.call(this, salutation);
}

function foo(salutation) {
alert(salutation + " " + this.name);
}

var t = new Thing('Joe');
t.doSomething(foo, 'Hi'); // Alerts "Hi Joe" via `foo`

Sometimes it's useful to pass the arguments you want to give the callback as an array, rather than individually. You can use apply to do that:

function Thing(name) {
this.name = name;
}
Thing.prototype.doSomething = function(callback) {
// Call our callback, but using our own instance as the context
callback.apply(this, ['Hi', 3, 2, 1]);
}

function foo(salutation, three, two, one) {
alert(salutation + " " + this.name + " - " + three + " " + two + " " + one);
}

var t = new Thing('Joe');
t.doSomething(foo); // Alerts "Hi Joe - 3 2 1" via `foo`

Javascript Custom Callback Function

You're getting confused between the Stack and the Queue.

The Event Loop

In javascript, synchronous calls are going into the stack while asynchronous calls are going into the Heap, and when done are back in the Queue. A function is moving from the Queue to the Stack only when it's empty.

Sample Image

In your example

phase 1: call setTimeout()

this puts the function in the heap, and since the timeout is set to 0, it right away moves to the _queue. does it means that it's executing right away? no, because that your current function (the "main") hasn't finished yet.

phase 2: call test()

this code is synchronous! when calling test we add a function to the stack. then we add the cb() call to the stack.
that means that we need to finish all both before we can proceed to phase 3.

phase 3: console.log

nothing to explain here

post phase 3

the current "main stack is finished, so the function from the queue is now added ti the stack, logging 'timeout'.

How to create callback in custom function using jquery

You're almost there...

function customFunction(a, b, callback) {
// Some code
if (typeof callback === 'function') {
callback();
}
}

customFunction("val1", "val2", function(){
//Code to execute after callback
});

JavaScript: custom callBack function

callback is simple function that is invoked when some works is complete, in javascript you can pass it in variable, so in your async/worker function you have to invoke callback function (like callback(result)) once it finishes the job.

so your code should be

function catchDataFromDB(db, tableName, callBack) {  var sqlStr = 'SELECT * FROM ' + tableName;  db.transaction(function(t) {      // Query out the data      t.executeSql(sqlStr, [], function(t, SQLResultSet) {        var len = SQLResultSet.rows.length,          row;        for (var i = 0; i < len; i++) {          row = SQLResultSet.rows.item(i);          sqlData.push(row);        }        callBack(null, sqlData);      });    },    function(SQLError) {      callBack(SQLError.message);    });}

custom web component callbacks

Update: Please try the below code, where I have added a binding statement to bind "this"

<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<xmp-1></xmp-1>
<script>
document.querySelector('xmp-1').action1 = function(){
console.log("this is the callback");
};
window.customElements.define('xmp-1', class xmp1 extends HTMLElement {
constructor() { super();
this.handler = this.handler.bind(this);
}
handler() {
console.log("this is the test");
console.log('test action');
this.action1();
}

connectedCallback() {
this.innerHTML = `<div>
<div id='test' style='width:70px; border:solid thin black;'>test button</div>
</div>`;
this.querySelector('#test').addEventListener('click',this.handler);
}
});
</script>
</body>
</html>

Please change xmp-1 to #test in your code as shown below,

<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<xmp-1></xmp-1>
<script>
window.addEventListener('load', (event) => {

document.querySelector('#test').action1 = function(){
console.log("this is the callback");
};

});
window.customElements.define('xmp-1', class xmp1 extends HTMLElement {
constructor() { super(); }

connectedCallback() {
this.innerHTML = `<div>
<div id='test' style='width:70px; border:solid thin black;'>test button</div>
</div>`;
this.querySelector('#test').addEventListener('click', function () {
console.log('test action');
this.action1();
});
}
});
</script>
</body>
</html>

Or please try approach2 as shown below, where you must add a function called this.querySelector('#test').action1 to your custom element.

<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<xmp-1></xmp-1>
<script>
window.customElements.define('xmp-1', class xmp1 extends HTMLElement {
constructor() { super(); }

connectedCallback() {
this.innerHTML = `<div>
<div id='test' style='width:70px; border:solid thin black;'>test button</div>
</div>`;
this.querySelector('#test').addEventListener('click', function () {
console.log('test action');
this.action1();
});
this.querySelector('#test').action1 = function() {
console.log('test action1');
}
}
});
</script>
</body>
</html>

How to create a custom callback

Define a parameter for your funcAsynch() function.

function funcAsynch(callback) {
// asynch operations
// invoke callback() when asynch is done
}

And pass the callback function to that parameter.

funcAsynch(function () { 
alert("all asynch operations are finished");
});

Javascript: Passing custom arguments to a callback function

Use an additional closure.

arr[c.name] = (function(url) { 
return function() { callback(url); }
})(c.url);

See Creating closures in loops: A common mistake and most other questions on this topic, and now your question is also added to this pool.

Giving a provided Node JS callback my own custom Callback

you can't quite do what you are doing, you are doing callCount(null, null, printCount) which executes the function. But you need to pass a function as a callback. What you want is something like the following, which captures the call back you want and returns a function you can pass as a callback to your api call

 var callCount = function(callback) {
return function(err, list) {
var count = 0;
if(err) throw err;
// console.log(err);
for (var i = 0; i < list.length; i++) {
// console.log(reqs.path.extname(list[i]));
if(reqs.path.extname(list[i]) === ".png" || reqs.path.extname(list[i]) === ".jpg")
{
count++;
console.log(count);
}
}
callback(count);
}
}

and then

reqs.fs.readdir(dirName, callCount(printCount));

Is there any way to use the values(Boolean) of two Callback functions in Node.js?

You mean to log the string once the test done?

Well you have to use nested callbacks to make it in your desired order.

So after first id in db check is done, proceed for next id check inside of the first id callback.


function testGetSchoolAdministrationById() {
var pass1,pass2;
databaseConnection.getSchoolAdministrationById(1, function (schoolAdministration) {

if(schoolAdministration.first_name == "Harald" &&
schoolAdministration.last_name == "Schmidt" &&
schoolAdministration.id_schoolAdmin == 1){

pass1=true;
databaseConnection.getSchoolAdministrationById(2, function (schoolAdministration) {
if(schoolAdministration.first_name == "Madeline" &&
schoolAdministration.last_name == "Müller" &&
schoolAdministration.id_schoolAdmin == 2){
pass2=true;

console.log("Test for getCompanyById() passed: " + (pass1 && pass2));

}
else {
console.log("Test for getCompanyById() passed: " + (pass1 && pass2));
}
}
);
}
else {
console.log("Test for getCompanyById() passed: " + (pass1 && pass2));
}
}
);

}



Related Topics



Leave a reply



Submit