Event listener in javascript - javascript

How to create a function that accepts the parameter as a function?
I have this function and I want to call it with parameter of a function also:
function ShowDialog(OnSubmit)
{
var _result = OnSubmit();
alert(_result);
}
This is what I want to call:
ShowDialog(
{
OnSubmit: function () {
return "Hello World";
}
}
);
this will alert "Hello World in browser"

Call:
ShowDialog(function(){
return "Hello World";
});
Then your function can remain as:
function ShowDialog(OnSubmit)
{
var _result = OnSubmit();
alert(_result);
}

JavaScript has first-class functions, so you can just pass the function reference directly, you do not need an object:
function showDialog(callback) {
var result = callback();
alert(result);
}
function bye() { return "bye!" };
showDialog(function() { return "Hello!" });
showDialog(bye);
var greetings = { ciao: function() { return "Ciao!" } };
showDialog(greetings.ciao);
Of course you can also pass the full object, in that case you need to modify the function as follow:
function showDialog(options) {
var result = options.onSubmit();
alert(result);
}
And then:
showDialog({
onSubmit: function() { return "Hello!" }
});
showDialog({
onSubmit: bye
});
You could also implement a function that accepts both object and callback:
function showDialog(options) {
var result = typeof options === 'function' ? options() : options.onSubmit();
alert(result);
}
showDialog({
onSubmit: bye
});
showDialog(bye);
Hope it helps.

Try this instead:
function ShowDialog(param)
{
var _result = param.OnSubmit();
alert(_result);
}
ShowDialog({
OnSubmit: function () {
return "Hello World";
}
});

Related

Call javascript function and obtain return value with anonymous function

I saw some JavaScript calling function like this:
$(hr).executeService('CCTV','CCTV',{'NVRAssetKey':nvrak,'cklst':cklst},function(data)
{
_ws = data[0]['WebServer'];
_cams = data[0]['Cameras'];
//...
}
);
How to create this type of function to get return value from the anonymous function ?
What I want to do :
Calculate( 1,2,function(sum){
console.log(sum);
});
I tried this code but not worked.
<script>
function doIt(param1) {
doIt2(param1, function (data) {
console.log(data);
});
}
function doIt2(param) {
return param;
}
</script>
<button onclick="doIt(Math.random());">Click</button>
Are you looking for this?
<script>
function Calculate(a, b, callback) {
var result = a + b;
return callback(result);
}
function doIt2(a, b) {
Calculate(a, b, function(data) {
console.log(data);
});
}
</script>
<button onclick="doIt2(5,10);">Click</button>

call function after .shift()

I'm creating an array of functions.
var wrapFunction = function(fn, context, params) {
return function() {
fn.apply(context, params);
};
}
var sayStuff = function(str) {
//do work & return something
return str;
}
var fun1 = wrapFunction(sayStuff, this, ["Hello, world!"]);
que = []
que.push(fun1);
Right now I'm doing this:
var current = que.shift()
current();
This works fine, but is there a way to call que.shift & run all the functions all the way down to my sayStuff function; so that
current === 'Hello, world!'
I tried (que.shift())(); but it doesn't trigger the whole cycle.
(que.shift())(); should work if you return the value of your fn.apply call:
return fn.apply(context, params);
You should add return in the anonymous function:
var wrapFunction = function(fn, context, params) {
return function() {
return fn.apply(context, params); // <-- Insert return here
};
};
Then,
que.shift()(); // "Hello, world!"

How to invoke a callback function with arguments

I have this main function which takes 1 string and 2 callback functions as the argument. Below is the code.
function confirmYesNo(confirmMessage, confirmCallback, cancelCallback) {
$("#yes-button").click(function () {
confirmCallback(); //How do I pass confirmCallback arguments
});
...
}
Here is how the function is invoked
function confirmYesNoTest() {
var confirmContent = "Some Message"
var id = "1";
confirmYesNo(confirmContent,
function (id) { alert(id); }, //alerts undefined
function () { alert("Cancel Clicked"); });
}
The problem is that the id variable above (which is set to 1) comes out as "undefined" when the confirmCallback executes. Seems something related to scope, but I am not able to get this working.
The callback should not take any arguments. You could capture the id in a closure:
function confirmYesNoTest() {
var confirmContent = "Some Message"
var id = "1";
confirmYesNo(
confirmContent,
function () { alert(id); },
function () { alert("Cancel Clicked"); }
);
}
Alternatively, if you didn't want to use closures you could pass the id as parameter to the callback:
function confirmYesNo(confirmMessage, id, confirmCallback, cancelCallback) {
$("#yes-button").click(function () {
confirmCallback(id);
});
...
}
and when invoking:
function confirmYesNoTest() {
var confirmContent = "Some Message"
var id = "1";
confirmYesNo(
confirmContent,
id,
function (id) { alert(id); },
function () { alert("Cancel Clicked"); }
);
}
Now you can use the callbacks as named functions:
var confirmCallback = function(id) {
alert(id);
};
and then:
function confirmYesNoTest() {
var confirmContent = "Some Message"
var id = "1";
confirmYesNo(
confirmContent,
id,
confirmCallback,
function () { alert("Cancel Clicked"); }
);
}

How to use a return value in another function in Javascript?

I'm self-teaching myself JavaScript and out of curiosity I'm wondering what is the proper way of returning a value from one function to be used in another function. For example:
function firstFunction() {
// do something;
return somevalue
}
So how do I set up the second function to use somevalue? Thanks.
Call the function and save the return value of that very call.
function firstFunction() {
// do something
return "testing 123";
}
var test = firstFunction(); // this will grab you the return value from firstFunction();
alert(test);
You can make this call from another function too, as long as both functions have same scope.
For example:
function testCase() {
var test = firstFunction();
alert(test);
}
Demo
You could call firstFunction from secondFunction :
function secondFunction() {
alert(firstFunction());
}
Or use a global variable to host the result of firstFunction :
var v = firstFunction();
function secondFunction() { alert(v); }
Or pass the result of firstFunction as a parameter to secondFunction :
function secondFunction(v) { alert(v); }
secondFunction(firstFunction());
Or pass firstFunction as a parameter to secondFunction :
function secondFunction(fn) { alert(fn()); }
secondFunction(firstFunction);
Here is a demo : http://jsfiddle.net/wared/RK6X7/.
Call function within other function :
function abc(){
var a = firstFunction();
}
function firstFunction() {
Do something;
return somevalue
}
You can do this for sure. Have a look below
function fnOne(){
// do something
return value;
}
function fnTwo(){
var strVal= fnOne();
//use strValhere
alert(strVal);
}
var captcha = '';
//function name one
function one(captcha){
var captcha = captcha;
//call another function and pass variable data
var captcha = firstFunction(captcha);
};
// second function name
function firstFunction(captcha){
alert(captcha);
}
To copy the return value of any javascript(in chrome console), we can use inbuilt copy() method.
you can use any expression, function, etc
find some examples below
using expresseion
a = 245;
copy(a);
using function
a = function() {
return "Hello world!"
}
copy(a());
Official Doc for reference

Javascript- Callback function issue from namespace?

var myNamespace = {
dateController: {}
};
myNamespace.dateController = function(callback) {
this.callbackfunction = callback;
try {
[this.callbackfunction]();
} catch (e) {
alert(e);
}
};
function displayDate() {
alert("displayDate");
myNamespace.dateController("displayDateFromController");
};
function displayDateFromController() {
alert("In displayDateFromController");
};
This piece of code is giving me TypeError: ["displayDateFromController"] is not a function error. What could be root cause and possible solution to this issue.
Why dateController not able to identify displayDateFromController as function.
I have tired this on
http://www.w3schools.com/js/tryit.asp?filename=tryjs_events
You need to pass the actual function to the datecontroller method instead of the String.
var myNamespace = {
dateController: {}
};
myNamespace.dateController = function (callback)
{
this.callbackfunction = callback;
try{
//remove [] surrounding function
this.callbackfunction();
}
catch(e)
{
alert(e);
}
};
//Declare this method prior to displayDate
function displayDateFromController()
{
alert("In displayDateFromController");
};
function displayDate()
{
alert("displayDate");
//Pass function instead of string
myNamespace.dateController(displayDateFromController);
};
displayDate();
Working Example: http://jsfiddle.net/RDMHV/
If you still need the flexibility of a String:
var myNamespace = {
dateController: {}
};
myNamespace.dateController = function (callback)
{
this.callbackfunction = this[callback];
try{
this.callbackfunction();
}
catch(e)
{
alert(e);
}
};
myNamespace.displayDateFromController = function(){
alert("In displayDateFromController");
};
function displayDate()
{
alert("displayDate");
myNamespace.dateController("displayDateFromController");
};
displayDate();
Working Example http://jsfiddle.net/RDMHV/1/
You have to remove the brackets around the call :
try{
this.callbackfunction();
}
catch(e)
{
alert(e);
}
and to pass the function without the quotes :
function displayDate()
{
alert("displayDate");
myNamespace.dateController(displayDateFromController);
};

Categories