Object literal pattern callback and this confusion - javascript

var App = {
method : function (value, callback) {
console.log(value);
if (typeof callback === 'function') {
//here
callback.call( this );
}
}
}
App.method('Hey there', function(){
console.log('callback was executed!');
});
Why do I can't do callback(), but have to call(this) for the callback?

To put it simply, you don't have to. Unless you want your callback function to have its context be the "App" object. For example:
// Regular callback:
var App = {
method : function (value, callback) {
if (typeof callback === 'function') {
callback();
}
}
}
App.method('Hey there', function(){
console.log(
'A regular callback was executed!',
'And its context is Window:',
this === window
);
});
// Context modified callback:
var App = {
method : function (value, callback) {
if (typeof callback === 'function') {
callback.call( this );
}
}
}
App.method('Hey there', function(){
console.log(
'A context modified callback was executed!',
'And its context is App:',
this === App
);
});
I hope that helps!

In the specific case of the callback function you're supplying, it would not matter if you invoked the callback simply with:
callback();
Your callback code does not refer to this at all, so it makes no difference what value it has.
If, however, the callback wanted to refer to other parts of the App object, then invoking with callback.call(this) would ensure that this refers to App in the callback. Example:
var App = {
method : function (value, callback) {
console.log(value);
if (typeof callback === 'function') {
//here
callback.call( this );
}
},
property: "HELLO WORLD"
}
App.method('Hey there', function(){
console.log('callback was executed! Property value is: ' + this.property);
});
With that code, this would have to refer to App in order for the console.log() call to access the object property. The use of .call() ensures that.

Related

Calling a namespaced callback function by name

This is probably basic... given a fully qualified function name, I'm trying to call it via .apply()
Superficial example
var ns = {
someFunc: function() { console.log('stuff'); }
}
function someTopLevelFunc() { console.log('top level'); }
Given a method that takes the name of that function, us there some way to call the namespaced function?
function theCaller(funcName) {
console.log("Callback name: " + callbackFunctionName)
const callbackFunction = window[callbackFunctionName];
console.log("Type: " + (typeof callbackFunction))
if((typeof callbackFunction) === "function") {
callbackFunction.apply(null, []);
}
}
theCaller('topLevelFunc');
theCaller('ns.someFunc');
The first call works while the second call shows the callbackFunction type as undefined
Probably a simple syntax issue, but my googling has failed me.

Jasmin test if callback parameter is called

so i have a function which checks if a checksum is changed and if so it calls the callback which is provided by a parameter.
var watchFileChange = function watchFileChange(oldChecksum, callback){
// some code about checking checksum
if(oldChecksum != newChecksum){
callback()
}
}
exports.watchFileChange = watchFileChange;
my Jasmin specs looks like this.
var t = require('../server.js');
describe("watchFileChange", function() {
spyOn(t.watchFileChange, 'Callback');
var file_false = {
'foo.txt': 'd41dcccc8f00b204e9800998ecf8427e'
}
var file_true = {
'foo.txt': 'd41d8cd98f00b204e9800998ecf8427e'
}
function Callback() {
console.log("Callback Called")
}
it("Checksum is not right, it should call Callback function", function() {
watchFileChange(file_false, Callback);
expect(Callback).toHaveBeenCalled();
});
});
But it just doesn't work that way because Callback is not defined i get that. So my question is there a way to check if the by parameter provided callback is called?
You can create a fake object where you can define you callback function, and then pass it as the argument
var init = {
callback: function() {
console.log("Callback Called")
}
};
describe("watchFileChange", function() {
beforeEach(function() {
spyOn(init, 'callback');
});
//...
it("Checksum is not right, it should call Callback function", function() {
watchFileChange(file_false, init.callback);
expect(init.callback).toHaveBeenCalled();
});
});

nodejs callback don't understand how callback result come through argument

Seen and run code below, thought I understand closures... How that 'avatarUrl' in callback argument is received in 'avatar'which is function argument too. I know this is common pattern, just can't get it yet
var GitHubApi = require('github');
var github = new GitHubApi({
version: '3.0.0'
});
var getUserAvataWithCallback = function(user, callback) {
github.search.users({q: user}, function(err,res) {
if (err) { callback(err, null);}
else {
var avatarUrl = res.items[0].avatar_url;
callback(null, avatarUrl);
}
});
};
getUserAvataWithCallback('irom77', function(err,avatar) {
console.log('got url with callback pattern', avatar);
})
So, callbacks are an underlying and integral concept in javascript, so it is important that you understand a few concepts. Look at this example:
// This is the function definition for "foo"
//here the callback argument refers to
//the second argument in the function call at
//the bottom which is a function
var foo = function(arg, callback) {
if(arg%2 != 0)
callback("arg is odd", arg)
else
callback(null, arg)
}
//Function call to foo
foo(2, function(err, num) {
if(err)
console.log(err)
else
console.log(num)
}
So, in the example above, you can think of the function call as a call with two parameters, the integer 2 and a function.
In the function definition:
The integer is referred to as "arg" and the function is referred to as "callback".
When callback("arg is odd", arg) is executed, the function is called with:
err = "arg is odd"
num = arg
When callback(null, arg) is executed, the function is called with:
err = null
num = arg
The important thing to remember here is that in javascript, functions can be passed as arguments to other functions. Do some further reading here.
The name of the argument passed to a function does not need to be the name of the argument in the definition of the function, the argument in the definition is the name of the variable that will be initialized inside the scope of given function. The argument declaration will receive the value passed at the second position of the function call (as per the code you've provided) and you will be able to access it inside the scope with that name. You can:
function foo(arg1, arg2) {
console.log(arg1, arg2);
}
foo(true, true); // will output true, true
foo(0, 1); //will output 0, 1
foo('shikaka', 1); //will output "shikaka", 1
var bar = "shikaka";
foo(bar, "shikaka"); //will output "shikaka", "shikaka"

call a callback in other callback js

I wondering if we can set a function containing a Callback function as parameter to another function who takes a callback too.
Example
function save(err, data, cb){};
function get(id, cb){};
get('12', save)?
Of course, a variable can be passed as argument of a function!
It may be clearer for you if you do:
// This also works with the notation `function save(...)`
var save = function(err, data, cb) {
alert('save' + err); // save12
},
get = function(id, cb) {
alert('get' + id); // get12
cb(id); // This call the "save" function
}
;
get('12', save);
Just be careful to not stack your callback too much or you will enter in the callback hell world!
Yes you can, check this example:
jsFiddle Example
jQuery(document).ready(function () {
function1({
param: "1",
callback: function () {
function2({
param : "2",
callback: function(){
alert("hello");
}
})
}
});
});
function function1(params){
alert(params.param);
params.callback();
}
function function2(params){
alert(params.param);
params.callback();
}
I hope it will be useful.

Function as a parameter javascript syntax

I have a function like this :
module.exports.download = function (cb) {
// Some Code
cb();
}
Is it the same to do this :
module.exports.copyimagefromalbumnext = function (callback) {
module.exports.download(callback);
}
or
module.exports.copyimagefromalbumnext = function (callback) {
module.exports.download( function () { callback(); } );
}
In advance thanks.
Is callback the same as function () { callback(); }
No. The second function neither cares about this context, passed arguments, nor the return value of an invocation. You could do
function() { return callback.apply(this, arguments); }
but that's just superfluous. Use the first approach and pass callback itself.

Categories

Resources