How to call the sub function into the main function - javascript

Apps Script
function Docs() {
this.getActions = function(p) {
console.log("get action calling")
}
I need to call the getActions function in Docs funtion

function Docs() {
this.getActions = function(p) {
Logger.log("get action calling")
}
this.callActions = function () {
this.getActions();
}
}
function test() {
var docs;
docs = new Docs();
docs.getActions();
docs.callActions();
}

Related

Passing parameters to a callback in javascript/nodejs

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');

Aframe pass variables between functions in component

I’m trying to stop the throttledFunction from running unless the “fly” event listener has been emitted. But I can’t change the “this.ballhit” variable from inside the eventlistener.
I don’t know how to pass variables between functions within the component.
AFRAME.registerComponent('ballflyact', {
init: function () {
var el = this.el;
this.ballhit = '';
el.addEventListener('fly', function () {
this.ballhit = true;
});
},
tick: function (t, dt) {
if (!this.ballhit) { return; }
this.throttledFunction(); // Called once a second.
},
});
When you create a function, this becomes different.
You can use self-binding function el.addEventListener('fly', () => { // ... });
Or like var self = this; el.addEventListener('fly', function () { self.ballHit = true; });
The following works. Thank you. Now the throttle function will only run for ~10,000 milliseconds after the “fly” event, not constantly in the background.
AFRAME.registerComponent('ballflyact', {
init: function () {
var el = this.el;
this.ballhit = '';
var self = this;
el.addEventListener('fly', function () {
self.ballhit = true;
// more code
setTimeout((e)=>{
self.ballhit = '';
}, 10000)
});
},
tick: function (t, dt) {
if (!this.ballhit) { return; }
this.throttledFunction(); // Called once a second.
},
});

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"); }
);
}

Event listener in 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";
}
});

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