I have a requirement where I get the anchor tags id and based on the id I determine which function to execute.. so is there anything that suites below code
function treeItemClickHandler(id)
{
a=findDisplay(id);
a();
}
You can assign a function to a variable like so:
You can also return a function pointer from a function - see the return statement of findDisplay(id).
function treeItemClickHandler(id)
{
var a= findDisplay;
var other = a(id);
other();
}
function findDisplay(id)
{
return someOtherThing;
}
function someOtherThing()
{
}
Sure, functions are first class objects in JavaScript. For example, you can create a map (an object) which holds references to the functions you want to call:
var funcs = {
'id1': function(){...},
'id2': function(){...},
...
};
function treeItemClickHandler(id) {
if(id in funcs) {
funcs[id]();
}
}
As functions are treated as any other value, you can also return them from another function:
function findDisplay(id) {
// whatever logic here
var func = function() {};
return func;
}
functions are normal javascript values, so you can pass them around, (re)assign them to variables and use them as parameter values or return values for functions. Just use them ;) Your code is correct so far.
You can map between ids and functions to call in a number of ways.
One of the simpler ones is to create an object mapping ids to functions, and find the function to call from that object (this is in essence a nicer-looking switch statement).
Example:
function treeItemClickHandler(id)
{
var idMap = {
"some-id": findDisplay,
"another-id": doSomethingElse
};
if (!idMap.hasOwnProperty(id)) {
alert("Unknown id -- how to handle it?");
return;
}
// Call the corresponding function, passing the id
// This is necessary if multiple ids get handled by the same func
(idMap[id])(id);
}
function findDisplay(id)
{
// ...
}
function doSomethingElse(id)
{
// ...
}
Related
I have a function called "destination" nested in scrip1.js file. If I add this file at the end of webpage using , how can I trigger it at the next step? Here are some contents of script1.js.
script1.js
$.something = function(element, options) {
function start() {
function destination(arg1, arg2..) {
$.notify(some args);
}
}
$("body").on("click", ".notify-btn", function (event) {
event.preventDefault();
destination(some args);
});
someOtherFunction();
start();
}
$.fn.something = function (options) {
return this.each(function () {
if (undefined == $(this).data("something")) {
var plugin = new $.something(this, options);
$(this).data("something", plugin);
}
});
};
I tried this, but is not working. Chrome console is showing error about this function.
<script type="text/javascript" src="script1.js"></script>
<script>
$.fn.something().destination();
</script>
I can not change this script1.js, so any possible way?
There's no specific connection between variables declared during function execution - and how the rest of the world sees the result of execution. So this code:
function start() {
function destination(arg1, arg2..) {
$.notify(some args);
}
}
start();
... lets destination value (remember, functions in JS are first-class citizens) go away when start() completes its execution. That's actually quite convenient if you want to encapsulate some implementation details and hide it from users; this technique (also known as Module pattern) was often used in pre-class world to implement private properties in vanilla JavaScript.
However, all the values returned from a function can be reused. For example, here...
$.something = function(element, options) {
function start() {
function destination(arg1, arg2..) {
$.notify(some args);
}
return {
destination
};
}
return start();
}
... you make destination function a part of object that is returned from start(). Now $.something returns an object, too; that means it can be reused:
var plugin = new $.something(this, options);
// ...
plugin.destination('some', 'args');
If you're afraid changing the return value might hurt someone, you can try to assign value of destination to $.something object itself as its property, like this:
$.something = function(element, options) {
function start() {
function destination(arg1, arg2..) {
$.notify(some args);
}
return destination;
}
// ...
const destination = start();
$.something.destination = destination;
}
The returned value is not modified, yet function is accessible. Still, that's not actually a good workaround; the biggest issue is that any subsequent calls on $.something will rewrite the value of that function, which might be not a good thing if its execution depends on some scoped variables.
While technically there's a way to fetch destination function code by parsing $.something source code, I really doubt it's worth the effort in your case.
I have a js file with many functions
function one(){
//do stuff
}
function two(){
//do stuff
}
function execute_top_one(){
//do stuff
}
function execute_top_two(){
//do stuff
}
and I need to create a function that executes, for example, all functions that start with (or contain) "execute_top" in the function name, instead of having to call all the functions manually like this
execute_top_one();
execute_top_two();
Any suggestion?
I would suggest that you do it in a little other way:
const functionStore = {
one: function() {
console.log('one')
},
two: function() {
console.log('two')
},
execute_top_one: function() {
console.log('execute_top_one')
},
execute_top_two: function() {
console.log('execute_top_two')
},
}
const execute_these = "execute_top"
const executeFunctions = (functionStore, filterString) => {
Object.entries(functionStore).forEach(([fnName, fn]) => {
if (fnName.indexOf(filterString) !== -1) {
fn()
}
})
}
executeFunctions(functionStore, execute_these)
The difference is that you gather your functions into one object (I called it functionStore, and then create the filtering string & function. As you see from the snippet, filtering an object's keys and values (called fnName & fn in my snippet) is quite easy - and inside the filtering you can call the functions stored.
It's one of those times where I want to do soemthing, but I'm not sure what it's called...
Hopefully, someone can help!
I have the following function:
function myfunction(object1, object2) { ... }
I want to pass another function onto object1 specifically using the .click method.
I can get this working easily with only one object within the function using the following:
function myFunction(object1) { ... }
$('button').click(function() {
// Passes along another function!
myFunction(anotherFunction());
});
How would someone approach this when there are 2 objects? I can't seem to get anything working. Any ideas? Or am I approaching this the wrong way?
Updated Answer
Assuming still:
function myFunction( function, anotherFunction, ... ) { ... }
If you want to pass specific arguments but be able to omit arguments, you could provide an argument but catch it as falsy:
myFunction( null, someOtherFunction, maybeAnotherFunction )
You then would need to handle the null, perhaps:
function myFunction( function, anotherFunction, ... ) {
let fnc = function;
let fnc2 = anotherFunction;
let ... = ...;
if(fnc) ...
if(fnc2) ...
if(...) ...
...
}
Original Answer
Because you are triggering the function immediately during its passing you might actually want to just send it without initializing it. Try the below and see if this works for you.
function myFunction(object1, object2) {
object1()
object2()
}
$('button').click(function() {
// Passes along another function!
myFunction(anotherFunction1, anotherFunction2);
});
var a = 5,
b = 2;
function check(val1, val2) {
console.log(val1);
console.log(val2);
}
function add() {
return a + b;
}
function mulitply() {
return a * b;
}
check(add, mulitply); // this will send refernce of function's not output
check(add(), mulitply()); // this will converts into like this check(7,10);
I want to implement a function that takes another function as an argument, and returns a new version of that function that can only be called once.
The first function works, but the 2nd one doesn't work.
Why doesn't the 2nd function work, but can somehow still access the word without a function inside it like the first one?
var logOnce = once(console.log)
function once(fn) {
var call = true;
return function(word) {
if(call) {
call = false;
return fn(word);
}
}
}
function once(fn) {
var call = true;
if (call === true) {
call = false;
return fn;
}
}
logOnce("foo"); ----> "foo"
logOnce("blue"); ----> "blue"
Your second approach doesn't work because it returns the same fn. In fact, it is equivalent to
function once(fn) {
return fn;
}
Therefore, once(console.log) is just console.log, and you can call it as many times as you want.
The first approach works because you return a different function, which will call the original one or not depending on a variable.
Just wondering if there is anyway to fire some code when a function is called, without adding the code to the function, for example:
function doSomething(){
//Do something
}
//Code to call when doSomething is called
You can wrap the function :
(function(){
var oldFunction = doSomething;
doSomething = function(){
// do something else
oldFunction.apply(this, arguments);
}
})();
I use an IIFE here just to avoid polluting the global namespace, it's accessory.
Well, yes, it's not actually hard to do. The crucial thing is that a function's name is just an identifier like any other. You can redefine it if you want to.
var oldFn = doSomething;
doSomething = function() {
// code to run before the old function
return oldFn.apply(this, arguments);
// code to run after the old function
};
NB that it's better to do oldFn.apply(this, arguments) rather than just oldFn. In many cases it won't matter, but it's possible that the context (i.e. the value of this inside the function) and the arguments are important. Using apply means they are passed on as if oldFn had been called directly.
What about something like:
function doSomething(){
doSomething.called = true;
}
//call?
doSomething();
if(doSomething.called) {
//Code to call when doSomething is called
}
I know you said you don't want to modify the original function, but consider adding a callback. Then you can execute code based on different results in your function (such as onSucess and onError):
function doSomething(onSuccess, onError){
try {
throw "this is an error";
if(onSuccess) {
onSuccess();
}
} catch(err) {
if(onError) {
onError(err);
}
}
}
Then, when you call doSomething, you can specify what you want done with inline functions:
doSomething(function() {
console.log("doSomething() success");
}, function(err) {
console.log("doSomething() error: " + err);
});