So basically i need to check if the est_wont_show was made/fulfilled/executed.
function est_wont_show() {
var HideThis, estpgt_id;
estpgt_id = $(this).attr("estpgt_id");
//Saving in DOM
HideThis = $("#estpgt_" + estpgt_id).detach();
HideThis = $("#estpt_tr_for_" + estpgt_id).detach();
if (document.body.getElementsByTagName(HideThis)) {
//Check if element is detached
alert("Element is in DOM");
}
}
Something in this way(this function is tied up to button)
function TEST_ALERT() {
if () {
//check if function was made
alert('hello');
} else {
alert('NO-2');
}
}
He should check because in the end there will be 2 things. Like if the elements ARE in DOM, then he will delete them, if they are not, then he will bring them back.
You can use a global scoped variable to know if it has been executed.
// We can use a flag to see if the function got executed
let est_wont_show_execution_flag = false;
function est_wont_show() {
// Do something ...
est_wont_show_execution_flag = true;
}
function TEST_ALERT() {
// Did est_wont_show has been executed ?
if (est_wont_show_execution_flag) {
console.log('TEST_ALERT : est_wont_show has been executed');
return;
}
console.log('TEST_ALERT : est_wont_show hasn\'t been executed');
}
TEST_ALERT();
est_wont_show();
TEST_ALERT();
You can use typeof operator to see if any function is available by the given name
function TEST_ALERT() {
if (typeof est_wont_show === "function") {
//check if function was made
alert('hello');
} else {
alert('NO-2');
}
}
If the function is not created typeof est_wont_show will be "undefined"
I'm trying to test in which function this callback function in executed. It should return a boolean value.
I hope you know what I mean.
Here the code example:
function test(par, callback) {
// ...
if (typeof callback == 'function') { // make sure the callback is a function
callback.call(this);
}
}
test("par", function() {
console.log("Test if in function test: " + "<if this is in function test>");
});
Is this similar to instanceof?
There's a non-standard way of doing it since the removal of arguments.caller
function test(par, callback) {
// ...
if (typeof callback == 'function') { // make sure the callback is a function
callback.call(this);
}
}
test("par", function cb() {
var isTestCaller = cb.caller === test;
console.log("Test if in function test: " + isTestCaller);
});
Another possible way doing it through error stacks (still non-standard):
var checkCaller = function(fnName) {
var e = new Error();
var caller = e.stack.split('\n')[2].trim().split(' ')[1];
return caller === fnName;
}
function wrapper(){
console.log(checkCaller('wrapper'));
}
wrapper();
Say I have a function like the following.
loadXML('Method', requestString, function(callback){
// The function as a callback parameter to loadXML goes here.
// Here I am calling the callback function like this
if(callback != null){
callback();
}
});
But I want to define this callback function inside the loadXML function. So can I do this as following?
loadXML('Method', requestString, function(callback){
// The function as a callback parameter to loadXML goes here.
// Here I have to call the callback function like this, (do I?) which is a
// callback parameter to callback function of loadXML
callback = function(){
// The callback function implementation goes here
}
});
Maybe this could help you to understand the nested callbacks mechanism:
var loadXML;
var outerCB;
var innerCB;
loadXML = function(method, requestString, cb) {
// pass the innerCB implementation as argument to the outer cb
if('undefined' !== typeof innerCB) {
cb(innerCB);
} else {
// in case innerCB would not be defined
cb(function() {
console.log('hi from anonymous cb')
});
}
};
innerCB = function() {
console.log('hi from innerCB cb!')
};
outerCB = function(callback) {
if('undefined' !== typeof callback) {
callback(); // innerCB();
} else {
console.log('no cb passed, do something else')
}
}
loadXML('Method', 'abcd', outerCB) // hi from innerCB cb!
JS:
$.fn.blink = function(times, duration) {
times = times || 2;
while (times--) {
this.fadeTo(duration, 0).fadeTo(duration, 1);
}
};
This makes blinking text. At last blink I want to execute a function so I changed it like this:
$.fn.blink = function(times, duration, callback) {
times = times || 2;
while (times--) {
this.fadeTo(duration, 0).fadeTo(duration, 1);
}
if (typeof callback == 'function') { // make sure the callback is a function
callback.call(this); // brings the scope to the callback
}
};
The execution of callback is not at the right place. It seems to be fired when blinking starts. Any ideas how to call the function at last blinking?
FIDDLE
I wrote you a fiddle. The problem with your code was, that the loop iterated through your blinking stuff to fast, and the complete function was called immediately.
$(document).ready(function () {
$('.blink').blink(5, 500, shout);
});
function shout() {
alert('finished blinking');
}
$.fn.blinkOnce = function (duration, callback) {
this.fadeTo(duration, 0).fadeTo(duration, 1, function () {
if (typeof callback == 'function') callback.call(this);
});
};
$.fn.blink = function (times, duration, callback) {
var toBlink = this;
var blinkComplete = function () {
times--;
if (times == 0) callback.call(this);
else toBlink.blinkOnce(duration, blinkComplete);
}
toBlink.blinkOnce(duration, blinkComplete);
return true;
};
http://jsfiddle.net/xgeLu/
jQuery animations have a complete callback argument since these methods are asynchronous
Try:
while (times--) {
this.fadeTo(duration, 0).fadeTo(duration, 1, function(){
/*last animation is complete*/
if (typeof callback == 'function') { // make sure the callback is a function
callback.call(this); // brings the scope to the callback
}
});
}
API Reference: http://api.jquery.com/fadeTo/
All I need to do is to execute a callback function when my current function execution ends.
function LoadData()
{
alert('The data has been loaded');
//Call my callback with parameters. For example,
//callback(loadedData , currentObject);
}
A consumer for this function should be like this:
object.LoadData(success);
function success(loadedData , currentObject)
{
//Todo: some action here
}
How do I implement this?
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`
It is good practice to make sure the callback is an actual function before attempting to execute it:
if (callback && typeof(callback) === "function") {
callback();
}
My 2 cent. Same but different...
<script>
dosomething("blaha", function(){
alert("Yay just like jQuery callbacks!");
});
function dosomething(damsg, callback){
alert(damsg);
if(typeof callback == "function")
callback();
}
</script>
function loadData(callback) {
//execute other requirement
if(callback && typeof callback == "function"){
callback();
}
}
loadData(function(){
//execute callback
});
function callback(e){
return e;
}
var MyClass = {
method: function(args, callback){
console.log(args);
if(typeof callback == "function")
callback();
}
}
==============================================
MyClass.method("hello",function(){
console.log("world !");
});
==============================================
Result is:
hello world !
Some of the answers, while correct may be a little tricky to understand. Here is an example in layman's terms:
var users = ["Sam", "Ellie", "Bernie"];
function addUser(username, callback)
{
setTimeout(function()
{
users.push(username);
callback();
}, 200);
}
function getUsers()
{
setTimeout(function()
{
console.log(users);
}, 100);
}
addUser("Jake", getUsers);
The callback means, "Jake" is always added to the users before displaying the list of users with console.log.
Source (YouTube)
If you want to execute a function when something is done. One of a good solution is to listen to events.
For example, I'll implement a Dispatcher, a DispatcherEvent class with ES6,then:
let Notification = new Dispatcher()
Notification.on('Load data success', loadSuccessCallback)
const loadSuccessCallback = (data) =>{
...
}
//trigger a event whenever you got data by
Notification.dispatch('Load data success')
Dispatcher:
class Dispatcher{
constructor(){
this.events = {}
}
dispatch(eventName, data){
const event = this.events[eventName]
if(event){
event.fire(data)
}
}
//start listen event
on(eventName, callback){
let event = this.events[eventName]
if(!event){
event = new DispatcherEvent(eventName)
this.events[eventName] = event
}
event.registerCallback(callback)
}
//stop listen event
off(eventName, callback){
const event = this.events[eventName]
if(event){
delete this.events[eventName]
}
}
}
DispatcherEvent:
class DispatcherEvent{
constructor(eventName){
this.eventName = eventName
this.callbacks = []
}
registerCallback(callback){
this.callbacks.push(callback)
}
fire(data){
this.callbacks.forEach((callback=>{
callback(data)
}))
}
}
Happy coding!
p/s: My code is missing handle some error exceptions
When calling the callback function, we could use it like below:
consumingFunction(callbackFunctionName)
Example:
// Callback function only know the action,
// but don't know what's the data.
function callbackFunction(unknown) {
console.log(unknown);
}
// This is a consuming function.
function getInfo(thenCallback) {
// When we define the function we only know the data but not
// the action. The action will be deferred until excecuting.
var info = 'I know now';
if (typeof thenCallback === 'function') {
thenCallback(info);
}
}
// Start.
getInfo(callbackFunction); // I know now
This is the Codepend with full example.
function LoadData(callback)
{
alert('the data have been loaded');
callback(loadedData, currentObject);
}
function login(email, password, callback) {
//verify the user
const users = [
{ email: "abc#gmail.com", password: "123" },
{ email: "xyz#gmail.com", password: "xyz" }
];
const user = users.find(
(user) => user.email === email && user.password === password
);
callback(user);
`enter code here`}
function redirect(user) {
if (user) {
//user is successfully logged in
console.log("user is successfully logged in ");
} else {
console.log("Incorrect credentials ");
}
}
login("abc#gmail.com", "123", redirect);
I hope this example will help everyone who wants to know about the callback in JS
Try:
function LoadData (callback)
{
// ... Process whatever data
callback (loadedData, currentObject);
}
Functions are first class in JavaScript; you can just pass them around.