Hi I'm trying to understand callbacks in javascript and have come across this code here from a tutorial that I'm following:
var EventEmitter = require('events');
var util = require('util');
function Greetr() {
this.greeting = 'Hello world!';
}
util.inherits(Greetr, EventEmitter);
Greetr.prototype.greet = function(data) {
console.log(this.greeting + ': ' + data);
this.emit('greet', data);
}
var greeter1 = new Greetr();
greeter1.on('greet', function(data) {
console.log('Someone greeted!: ' + data);
});
greeter1.greet('Tony');
Now I notice that the greeter1.on function takes a callback with a parameter. However I'm not sure how this is implemented internally. I tried looking through the nodejs event.js file but I'm still confused. I am aware that there are ways around this specific implementation by using an anonymous function wrapping the callback with parameters but I want to understand how to use the same format as above.
tldr: How can I create my own function that takes a callback and a parameter in the same fashion as greeter1.on above.
Thank you
Your function needs to define a new property on the current instance with the callback passed as an argument, so it can be called later, like so:
function YourClass () {
this.on = function(key, callback) {
this[key] = callback;
}
}
// Usage
const instance = new YourClass();
instance.on('eventName', function (arg1, arg2) {
console.log(arg1, arg2);
});
instance.eventName("First argument", "and Second argument")
// logs => First argument and Second argument
Callback is just passing a function as a parameter to another function and that being triggered. You can implement callback fashion as below
function test(message, callback) {
console.log(message);
callback();
}
//Pass function as parameter to another function which will trigger it at the end
test("Hello world", function () {
console.log("Sucessfully triggered callback")
})
class MyOwnEventHandler {
constructor() {
this.events = {};
}
emit(evt, ...params) {
if (!this.events[evt]) {
return;
}
for (let i = 0, l = this.events[evt].length; i < l; i++) {
if (!params) {
this.events[evt][i]();
continue;
}
this.events[evt][i](...params);
}
}
on(evt, eventFunc) {
if (!this.events[evt]) {
this.events[evt] = [];
}
this.events[evt].push(eventFunc);
}
}
var myHandler = new MyOwnEventHandler();
myHandler.on('test', function (...params) {
console.log(...params);
});
myHandler.emit('test', 'Hello', 'World');
Related
I have a section in my code that looks like this
var locationDefer = $.Deferred();
if (saSel.Company === -1) {
database.getAllLocations().then(function (result) {
var locations = JSON.parse(result.d);
locationDefer.resolve(locations);
});
} else {
database.getLocationsForCompany(saSel.Company).then(function (result) {
var locations = JSON.parse(result.d);
locationDefer.resolve(locations);
});
}
However, since it is basically the same thing twice, just with a different ajax call - is there any way to either have the anonymous function part
function (result) {
var locations = JSON.parse(result.d);
locationDefer.resolve(locations);
})
declared as a real function and then just called in the .then() clause, or can I somehow provide the to-be-called-function of the database object?
For the latter, I had something in my mind that could look like this, but I have no clue how to do the last line.
if(saSel.Company === -1) {
fun = 'getAllLocations';
arg = null;
} else {
fun = 'getLocationsForCompany';
arg = saSel.Company;
}
// database.fun(arg).then(function (result) {...});
You can define a function and pass its reference as success callback handler
//Define the function handler
function resultHandler(result) {
var locations = JSON.parse(result.d);
locationDefer.resolve(locations);
}
if (saSel.Company === -1) {
fun = 'getAllLocations';
arg = null;
} else {
fun = 'getLocationsForCompany';
arg = saSel.Company;
}
//Invoke the method using Bracket notation
//And, pass the success handler as reference
database[fun](arg).then(resultHandler);
Additionally, as getLocationsForCompany() and getAllLocations() returns a promise, you shouldn't use $.Deferred() directly return Promise
return database[fun](arg);
**Made changes to example to correct a syntax error (all bold), thanks Luc DUZAN for the help. Changed c.target.result to the actual array used to hold the data 'objCollection' in the every last code example.
Problem: I would like to add an argument to a callback that already has parameters.
For this problem, I have functionality that calls a function, DataLayer.GetData, and executes a callback on completion. I pass this callback, LoadResults, with two existing parameter into the function DataLayer.GetData inside an enclosure. The callback function, LoadResults, correctly gets called from DataLayer.GetData and the parameters originally assigned in the calling functionality are correctly passed into LoadResults.
Is there a generic way or industry standard I can unpack the callback add the c.target.result argument and then call the callbackOnComplete callback so that c.target.result ends up as the dataResults argument in LoadResults?
Calling functionality:
var dbCallback = function () { LoadResults('530', material.Id); };
DataLayer.GetData('530', 'TypeIndex', dbCallback);
Data tier function:
DataLayer.GetData = function (indexKey, indexName, callbackOnComplete) {
var _this = this;
var objCollection = new Array();
try {
var trans = _this.transaction(['objectStoreName'], "readonly");
var store = trans.objectStore('objectStoreName');
var index = store.index(indexName);
var request = index.openCursor(indexKey);
request.onerror = function (e) {
...
}
request.onsuccess = function (e) {
var cursor = e.target.result;
if (cursor) {
objCollection.push(cursor.value);
cursor.continue();
}
}
trans.oncomplete = function (c) {
if (callbackOnComplete) callbackOnComplete();
else ...
}
}
catch (e) {
...
return false;
}
}
Callback function:
LoadResults = function(formType, materialCode, dataResults) {
...
}
What I would like to be able to accomplish within the DataLayer.GetData / trans.oncomplete event is add the argument objCollection to the callbackOnComplete callback list of arguments. Something like:
callbackOnComplete.arguments.push(objCollection);
Or is there another means of passing in a callback and its parameters?
Solution identified by Luc DUZAN:
Calling functionality:
DataLayer.GetData.bind(null, '530', material.Id));
Data tier function:
DataLayer.GetData = function (indexKey, indexName, callbackOnComplete) {
var _this = this;
var objCollection = new Array();
try {
var trans = _this.transaction(['objectStoreName'], "readonly");
var store = trans.objectStore('objectStoreName');
var index = store.index(indexName);
var request = index.openCursor(indexKey);
request.onerror = function (e) {
...
}
request.onsuccess = function (e) {
var cursor = e.target.result;
if (cursor) {
objCollection.push(cursor.value);
cursor.continue();
}
}
trans.oncomplete = function (c) {
if (callbackOnComplete) callbackOnComplete.apply(null, [objCollection]);
else ...
}
}
catch (e) {
...
return false;
}
}
Callback function:
LoadResults = function(formType, materialCode, dataResults) {
...
}
In a first time, you should provide to GetData a callback that only require arguments from c.target.result.
It should not be the concern of your GetData to deal with callback that take others parameters.
You can do that easily in ES5 with Function.prototype.bind:
DataLayer.GetData('530', 'TypeIndex', LoadResults.bind(null, '530', material.id));
Then in GetData, you only concern is too call your callback with value from c.target (which if I understood well is an array). For you can use Function.prototype.apply:
callbackOnComplete.apply(null, c.target);
For example if c.target is [1,2,3], this line will be equivalent to:
callbackOnComplete(1,2,3)
I am getting an error that I do not understand. I am calling async.waterfall with an array of functions. The function is 'shortened' for clarity.
FabricCommand.prototype.do = function (callback, undoArray) {
var self = this;
if (undoArray === undefined) {
undoArray = [];
}
undoArray.push(self);
callback(null, undoArray);
};
I create the array as listed below: doCommands is an array and the objects are added as such:
doCommands.push(fabricCommand.do.bind(fabricCommand));
the waterfall setup:
async.waterfall(
doCommands,
function(err, undoCommands){
if (err) {
// do something ...
}
else {
console.log('we succeeded with all the do commands... and there are '
+ undoCommands.length
+ ' in the undoCommands but we will disregard it...');
}
}
);
Now when I run this code, the first time through the FabricCommand.do function, I allocate the undoCommands array and I add one to it, next time through I get, where I try to add the array element, the following error:
undoArray.push(something);
^ TypeError: Object function (err) {
if (err) {
callback.apply(null, arguments);
callback = function () {};
}
else {
var args = Array.prototype.slice.call(arguments, 1);
var next = iterator.next();
if (next) {
args.push(wrapIterator(next));
}
else {
args.push(callback);
}
async.setImmediate(function () {
iterator.apply(null, args);
});
}
} has no method 'push'
Can anyone see what I am doing wrong?
The function that is executed by async.waterfall must have the following signature:
function(arg, callback) { … }
or, with multiple arguments:
function(arg1, arg2, callback) { … }
In your case, you simply inverted the two parameters:
FabricCommand.prototype.do = function (callback, undoArray) { … }
callback received the value intended to be stored in undoArray, and undoArray received the value intended for the callback, i.e. a function: that's why you encountered this weird error (function […] has no method 'push').
You need to put the parameters in the correct order:
FabricCommand.prototype.do = function (undoArray, callback) { … }
A second issue is that the first function of the waterfall receives only one parameter: the callback (because there is no value to be received, as it is the first function of the waterfall). A solution is to check the number of arguments:
if (Array.prototype.slice.apply(arguments).length === 1) {
callback = undoArray;
undoArray = undefined;
}
Here is a working gist.
I got some methods (methA, methB ...) that need to call the same method methMain in Javascript. This method methMain then need to fetch some data and when it is done do a callback to the method that called it (methA or MethB ...).
I can successfully create a pointer/reference to a method by using what is written here: How can I pass a reference to a function, with parameters?
That solution, and all others I have seen, does not seem to work in the current scope.
This code will not work:
function TestStructure() {
this.gotData = false;
//define functions
this.methA = function (parA) { };
this.methB = function (parb) { };
this.createFunctionPointer = function (func) { };
this.createFunctionPointer = function (func /*, 0..n args */) {
var args = Array.prototype.slice.call(arguments, 1);
return function () {
var allArguments = args.concat(Array.prototype.slice.call(arguments));
return func.apply(this, allArguments);
};
};
this.methA = function (parA) {
alert('gotData: ' + this.gotData + ', parA: ' + parA);
if (this.gotData == false) {
var fp = this.createFunctionPointer(this.methA, parA);
this.methMain(fp);
return;
}
//...do stuff with data
}
this.methB = function (parB) {
alert('gotData: ' + this.gotData + ', parB: ' + parB);
if (this.gotData == false) {
var fp = this.createFunctionPointer(this.methB, parB);
this.methMain(fp);
return;
}
//...do stuff with data
}
this.methMain = function (func) {
//...get some data with ajax
this.gotData = true;
//callback to function passed in as parameter
func();
}
}
var t = new TestStructure();
t.methA('test');
When methMain do a callback to func (methA or methB) the variable this.gotData will not be set.
Is there a solution for this problem or do I need to re-think the design?
I want to do this to get data with ajax without blocking with async: false.
I am not 100% sure but I think you can solve your problem by doing
this.createFunctionPointer = function (func /*, 0..n args */) {
var args = Array.prototype.slice.call(arguments, 1);
var that = this; //<<< here
return function () {
var allArguments = args.concat(Array.prototype.slice.call(arguments));
return func.apply(that, allArguments);
//here ^^^
};
};
This will cause your partially evaluated function to be called with the same this that created the function pointer. If you want a different scope just change whatever you pass to .apply.
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.