How to use a named function with for each and this - javascript

I have found that not using anonymous functions has made my code more readable and self-documenting by flattening the code into more understandable, standalone functions. So I'd like to break out the following construct from:
function Save() {
myVal = 3.14 // some arbitrary value
$('#myID').each(function(index,element) {
if ($(this).val() === myVal) {}
});
}
Into:
function Save() {
myVal = 3.14 // some arbitrary value
$('#myID').each(myFunction);
}
function myFunction(index,element) {
if ($(this).val() === myVal) {}
}
The problem with using .bind here, is that you lose the value of $(this) inside the each method, so (I don't think) I can bind myVal to myFunction.
Maybe I could use element instead of this?
Edit 1: I should have used .myClass instead of #myID for an example selector.
Edit 2: I'm not using bind in the proposed solution because I don't think bind would work.
Edit 3: I appreciate everyone saying that the first example is more readable. I'm just exploring the language and trying out different thoughts.

And what about :
function Save() {
myVal = 3.14 // some arbitrary value
$('#myID').each(myFunction(myVal));
}
function myFunction(myVal) {
return function(index, element) {
if ($(this).val() === myVal) {}
}
}

You're not losing access to this; you're losing access to myVal because myVal is not known inside myFunction, mainly due to that function being defined in a scope that does not have a definition for myVal.
What you can do is something like this:
function myFunction(index, element, myVal) {
if ($(this).val() === myVal) {}
}
and then:
function Save() {
myVal = 3.14 // some arbitrary value
$('#myID').each(function(index, element) {
myFunction.call(this, index, element, myVal);
});
}
This way if you have a lot of logic inside myFunction, you can still separate it out and just call myFunction from .each)'s callback. Not that myFunction is being called with .call because that way you can pass in an explicit value for this (the first argument). Hence this is the same this that is inside the callback to .each.
To be honest though, the first option is much more readable and you really aren't gaining much by splitting your code out like this.

this in this context will be the same. The one thing you lose access to is myVal. You are right that you can't use Function.bind because that does not allow you to specify to keep the original (call time) this
Here's how you can pass myVal and keep the same this, using a modified version of Function.bind, that we're calling myBind
/**
* Binds the given function to the given context and arguments.
*
* #param {function} fun The function to be bound
* #param {object} context What to use as `this`, defaults
* to the call time `this`
* #param {object[]} customArgs Custom args to be inserted into the call
* #param {number} index Where to insert the arguments in relationship
* to the call time arguments, negative numbers count from the end.
That is, -1 to insert at the end. Defaults to a 0 (beginning of list).
*
*/
function myBind(fun, context, customArgs, index) {
return function() {
// Default the index
index = index || 0;
// Create the arguments to be passed, using an old trick
// to make arguments be a real array
var newArgs = Array.prototype.slice.call(arguments, 0);
// Tack the customArgs to the call time args where the user requested
var spliceArgs = [index, 0].concat(customArgs);
newArgs.splice.apply(newArgs, spliceArgs);
// Finally, make that call
return fun.apply(context || this, newArgs);
}
}
function Save() {
myVal = 3.14 // some arbitrary value
$('#myID').each(
// myFunction wil be called with myVal as its last parameter
myBind(myFunction, null, [myVal], -1)
);
}
function myFunction(index, element, myVal) {
if ($(this).val() === myVal) {
// do it here
}
}
To demonstrate the flexibility of this function, let's bind more than one argument, and it should be inserted at the beginning of the call time arguments
function Save() {
var myVal = 3.14, val2 = 6.28; // some arbitrary values
$('#myID').each(
// myFunction wil be called with myVal and val2 as its first parameter
myBind(myFunction, null, [myVal, val2], 0);
);
}
// Since I don't need element, it's already available as this, we don't
// declare the element parameter here
function myFunction(myVal, val2, index) {
if ($(this).val() === myVal || $(this.val() === val2)) {
// do it here
}
}
This is almost the same answer as Samuel Caillerie. The only difference is that we create a different version of Function.bind that doesn't bind this, just the arguments. Another benefit of this version is that you can choose where the insert the bound arguments;

Related

Variable number of arguments in a function

Is it possible to tell a function what names it should give to its arguments, based on the number of arguments passed? Like this:
function soSwag(swagLevel, swagStart, swagDuration || swagStart, swagStop){}
What some popular libraries (e.g. jQuery) that support variable types of arguments do is that they examine the arguments and then swap values accordingly:
function soSwag(swagLevel, swagStart, swagDuration) {
if (arguments.length === 2) {
var swagStop = swagStart; // 2nd arg becomes swagStop
swagStart = swagLevel; // first arg becomes swagStart
// code here that uses swagStart and swagStop
// as called like soSwag(swagStart, swagStop)
} else {
// code here that uses swagLevel, swagStart, swagDuration
// as called like soSwag(swagLevel, swagStart, swagDuration)
}
}
Not to my knowledge. However, you can just pass in an object with the data you want.
soSwag({
swagStart: 10,
swagStop: 100
});
However, it might be cleaner to simply pass null into that first parameter.

how to add an argument to a method stored in an array that is called later

This is a follow-up to this question (although this is self-contained) trying to `call` three methods but not working correctly with jQuery map.
I am trying to store a set of methods in an array but there is a set that might have arguments like below (the initial methods are in before_methods and the proposed methods are in lm_methods). I'm sure it's pretty self explanatory what I want but I'd like to be able to merge in the arguments into a reasonable call to f (specifically the arc.pLikedByTerm). I currently have the following:
// signature
pLikedByTerm:function(term, ne, sw, m){
....
}
// code before_methods just to show
this.before_methods=[arc.pLocations,arc.pLikedLocations,arc.pLikedItems];
this.lm_methods=[arc.pLocations,arc.pLikedLocations,arc.pLikedItems, arc.pLikedByTerm('surfing'),arc.pLikedByTerm('sailing')];
$.each(this.lm_methods, function(i,f){
f(ne,sw,m);
});
How would I do this or is this bad design? What would be the idiomatic way? My brain is fried.
thx in advance
Update 1
Playing around with answer below, it looks like this works which might the simplest things:
var fns=[logStuff("this is msg"), logMoreArgs("a term","a you msg")];
for (var i=0; i<fns.length; i++) {
fns[i];
}
Having an array of functions is common practice when used often. For example, consider this Callback class.
function Callback(){
this.callbacks = [];
}
Callback.prototype.run = function(cb) {
for (var i=0; i<this.callbacks.length; i++) {
this.callbacks[i]();
}
};
We can then add some callbacks.
function logStuff(msg) {
jsprint(msg || "No message");
}
obj = new Callback();
obj.callbacks.push(logStuff);
obj.callbacks.push(logStuff);
obj.run();
If we run this we see that it's only logging our default value. So if we want to bind some data, we can use the bind function.
Function.prototype.bind
thisArg
The value to be passed as the this parameter to the target
function when the bound function is called. The value is ignored if
the bound function is constructed using the new operator.
arg1, arg2, ...
Arguments to prepend to arguments provided to the bound function
when invoking the target function.
Our new code sets the first parameter to different strings, which we then see. You can bind any number of parameters.
obj = new Callback();
obj.callbacks.push(logStuff.bind(null, "My message"));
obj.callbacks.push(logStuff.bind(null, "My other message"));
obj.run();
end result
The way you are doing would work just ok. Just remove the arguments and parens:
Instead of:
this.lm_methods=[arc.pLocations,arc.pLikedLocations,arc.pLikedItems,
arc.pLikedByTerm('surfing'),arc.pLikedByTerm('sailing')];
Do:
this.lm_methods=[arc.pLocations,arc.pLikedLocations,arc.pLikedItems,
arc.pLikedByTerm,arc.pLikedByTerm];
Example:
function say(txt) {
console.log("say" + txt);
}
function shout(txt) {
console.log("shout" + txt);
}
function whisper(txt) {
console.log("whisper" + txt);
}
var funcArr = [say, shout, whisper];
$.each(funcArr, function(i, f) {
f("hello");
});
would print:
sayhello
shouthello
whisperhello

How do I pass an extra parameter to the callback function in Javascript .filter() method?

I want to compare each string in an Array with a given string. My current implementation is:
function startsWith(element) {
return element.indexOf(wordToCompare) === 0;
}
addressBook.filter(startsWith);
This simple function works, but only because right now wordToCompare is being set as a global variable, but of course I want to avoid this and pass it as a parameter. My problem is that I am not sure how to define startsWith() so it accepts one extra parameter, because I dont really understand how the default parameters it takes are passed. I've tried all the different ways I can think of and none of them work.
If you could also explain how the passed parameters to 'built in' callback functions (sorry, I dont know of a better term for these) work that would be great
Make startsWith accept the word to compare against and return a function which will then be used as filter/callback function:
function startsWith(wordToCompare) {
return function(element) {
return element.indexOf(wordToCompare) === 0;
}
}
addressBook.filter(startsWith(wordToCompare));
Another option would be to use Function.prototype.bind [MDN] (only available in browser supporting ECMAScript 5, follow a link for a shim for older browsers) and "fix" the first argument:
function startsWith(wordToCompare, element) {
return element.indexOf(wordToCompare) === 0;
}
addressBook.filter(startsWith.bind(this, wordToCompare));
I dont really understand how the default parameters it takes are passed
There is nothing special about it. At some point, filter just calls the callback and passes the current element of the array. So it's a function calling another function, in this case the callback you pass as argument.
Here is an example of a similar function:
function filter(array, callback) {
var result = [];
for(var i = 0, l = array.length; i < l; i++) {
if(callback(array[i])) { // here callback is called with the current element
result.push(array[i]);
}
}
return result;
}
The second parameter of filter will set this inside of the callback.
arr.filter(callback[, thisArg])
So you could do something like:
function startsWith(element) {
return element.indexOf(this) === 0;
}
addressBook.filter(startsWith, wordToCompare);
For those looking for an ES6 alternative using arrow functions, you can do the following.
let startsWith = wordToCompare => (element, index, array) => {
return element.indexOf(wordToCompare) === 0;
}
// where word would be your argument
let result = addressBook.filter(startsWith("word"));
Updated version using includes:
const startsWith = wordToCompare => (element, index, array) => {
return element.includes(wordToCompare);
}
function startsWith(element, wordToCompare) {
return element.indexOf(wordToCompare) === 0;
}
// ...
var word = "SOMETHING";
addressBook.filter(function(element){
return startsWith(element, word);
});
You can use the arrow function inside a filter, like this:
result = addressBook.filter(element => element.indexOf(wordToCompare) === 0);
Arrow functions on MDN
An arrow function expression has a shorter syntax compared to function expressions and lexically binds the this value (does not bind its own this, arguments, super, or new.target). Arrow functions are always anonymous. These function expressions are best suited for non-method functions and they can not be used as constructors.
For anyone wondering why their fat arrow function is ignoring [, thisArg], e.g. why
["DOG", "CAT", "DOG"].filter(animal => animal === this, "DOG")
returns []
it's because this inside those arrow functions are bound when the function is created and are set to the value of this in the broader encompassing scope, so the thisArg argument is ignored. I got around this pretty easily by declaring a new variable in a parent scope:
let bestPet = "DOG";
["DOG", "CAT", "DOG"].filter(animal => animal === bestPet);
=> ["DOG", "DOG"]
Here is a link to some more reading:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_separate_this
based on oddRaven answer
and
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
i did it 2 different way .
1) using function way .
2) using inline way .
//Here is sample codes :
var templateList = [
{ name: "name1", index: 1, dimension: 1 } ,
{ name: "name2", index: 2, dimension: 1 } ,
{ name: "name3", index: 3, dimension: 2 } ];
//Method 1) using function :
function getDimension1(obj) {
if (obj.dimension === 1) // This is hardcoded .
return true;
else return false;
}
var tl = templateList.filter(getDimension1); // it will return 2 results. 1st and 2nd objects.
console.log(tl) ;
//Method 2) using inline way
var tl3 = templateList.filter(element => element.index === 1 || element.dimension === 2 );
// it will return 1st and 3rd objects
console.log(tl3) ;
There is an easy way to use the filter function, access all params, and not over complicate it.
Unless the callback's thisArg is set to another scope filter does not create its own scope, and we can access params within the current scope. We can set 'this' to define a different scope in order to access other values if needed, but by default it is set to the scope it's called from. You can see this being used for Angular scopes in this stack.
Using indexOf is defeating the purpose of filter, and adding more overhead. Filter is already going through the array, so why do we need to iterate through it again? We can instead make it a simple pure function.
Here's a use-case scenario within a React class method where the state has an array called items, and by using filter we can check the existing state:
checkList = (item) => { // we can access this param and globals within filter
var result = this.state.filter(value => value === item); // returns array of matching items
result.length ? return `${item} exists` : this.setState({
items: items.push(item) // bad practice, but to keep it light
});
}

Passing parameter to invoked event handler, i.e. element.onchange(); javascript

I have a function like this:
function doSomething()
{
// do something with select element
}
document.getElementById("selectel").onchange = doSomething;
// Call onchange event
document.getElementById("selectel").onchange();
Now, I recognize that I could call the function directly and pass a parameter. But I'd like to know if it's possible to pass a parameter to the onchange() event handler after it's evoked. I tried
document.getElementById("selectel").onchange("hello");
, but this didn't work.
Thank you for your help.
You need to bind a parameter to your function. I'm going to copy paste a function from Ext-JS that lets you do just that. Warning: not for beginners
/**
* Create a new function from the provided <code>fn</code>, change <code>this</code> to the provided scope, optionally
* overrides arguments for the call. (Defaults to the arguments passed by the caller)
*
* #param {Function} fn The function to delegate.
* #param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which the function is executed.
* <b>If omitted, defaults to the browser window.</b>
* #param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
* #param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
* if a number the args are inserted at the specified position
* #return {Function} The new function
*/
function bind(fn, scope, args, appendArgs) {
var method = fn,
applyArgs;
return function() {
var callArgs = args || arguments;
if (appendArgs === true) {
callArgs = Array.prototype.slice.call(arguments, 0);
callArgs = callArgs.concat(args);
}
else if (typeof appendArgs == 'number') {
callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
applyArgs = [appendArgs, 0].concat(args); // create method call params
Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
}
return method.apply(scope || window, callArgs);
};
}
You can use it like
function onChange(e, customParameter) {
// Whatever code
}
document.getElementById("selectel").onchange = bind(onChange, null, ["customParameter"], true);
When your handler is called, additional parameters are appended to the arguments passed by the event handler (the event object).
There's a lot of meat in this function, so feel free to ask any additional questions.
Here's a jsfiddle to see it in action http://jsfiddle.net/yBhG6/
Declare an anonymous function:
document.getElementById("selectel").onchange = function() { doSomething("hello"); }
You could use the apply() method which lets you pass arguments.
doSomething.apply(document.getElementById("selectel"), "hello");
I can see two approach to this question.
One is to call Your callback directly by passing select as this:
doSomething.apply(document.getElementById("selectel"), "Hello");
Second is similar to Igor's, but with help of other variables:
var param = "foo"; // Whatever default is
document.getElementById("selectel").onchange = function() {
doSomething(param);
}
param = "hello";
document.getElementById("selectel").onchange();

Handling optional parameters in javascript

I have a static javascript function that can take 1, 2 or 3 parameters:
function getData(id, parameters, callback) //parameters (associative array) and callback (function) are optional
I know I can always test if a given parameter is undefined, but how would I know if what was passed was the parameter or the callback?
What's the best way of doing this?
Examples of what could be passed in:
1:
getData('offers');
2:
var array = new Array();
array['type']='lalal';
getData('offers',array);
3:
var foo = function (){...}
getData('offers',foo);
4:
getData('offers',array,foo);
You can know how many arguments were passed to your function and you can check if your second argument is a function or not:
function getData (id, parameters, callback) {
if (arguments.length == 2) { // if only two arguments were supplied
if (Object.prototype.toString.call(parameters) == "[object Function]") {
callback = parameters;
}
}
//...
}
You can also use the arguments object in this way:
function getData (/*id, parameters, callback*/) {
var id = arguments[0], parameters, callback;
if (arguments.length == 2) { // only two arguments supplied
if (Object.prototype.toString.call(arguments[1]) == "[object Function]") {
callback = arguments[1]; // if is a function, set as 'callback'
} else {
parameters = arguments[1]; // if not a function, set as 'parameters'
}
} else if (arguments.length == 3) { // three arguments supplied
parameters = arguments[1];
callback = arguments[2];
}
//...
}
If you are interested, give a look to this article by John Resig, about a technique to simulate method overloading on JavaScript.
Er - that would imply that you are invoking your function with arguments which aren't in the proper order... which I would not recommend.
I would recommend instead feeding an object to your function like so:
function getData( props ) {
props = props || {};
props.params = props.params || {};
props.id = props.id || 1;
props.callback = props.callback || function(){};
alert( props.callback )
};
getData( {
id: 3,
callback: function(){ alert('hi'); }
} );
Benefits:
you don't have to account for argument order
you don't have to do type checking
it's easier to define default values because no type checking is necessary
less headaches. imagine if you added a fourth argument, you'd have to update your type checking every single time, and what if the fourth or consecutive are also functions?
Drawbacks:
time to refactor code
If you have no choice, you could use a function to detect whether an object is indeed a function ( see last example ).
Note: This is the proper way to detect a function:
function isFunction(obj) {
return Object.prototype.toString.call(obj) === "[object Function]";
}
isFunction( function(){} )
You should check type of received parameters. Maybe you should use arguments array since second parameter can sometimes be 'parameters' and sometimes 'callback' and naming it parameters might be misleading.
I know this is a pretty old question, but I dealt with this recently. Let me know what you think of this solution.
I created a utility that lets me strongly type arguments and let them be optional. You basically wrap your function in a proxy. If you skip an argument, it's undefined. It may get quirky if you have multiple optional arguments with the same type right next to each other. (There are options to pass functions instead of types to do custom argument checks, as well as specifying default values for each parameter.)
This is what the implementation looks like:
function displayOverlay(/*message, timeout, callback*/) {
return arrangeArgs(arguments, String, Number, Function,
function(message, timeout, callback) {
/* ... your code ... */
});
};
For clarity, here is what is going on:
function displayOverlay(/*message, timeout, callback*/) {
//arrangeArgs is the proxy
return arrangeArgs(
//first pass in the original arguments
arguments,
//then pass in the type for each argument
String, Number, Function,
//lastly, pass in your function and the proxy will do the rest!
function(message, timeout, callback) {
//debug output of each argument to verify it's working
console.log("message", message, "timeout", timeout, "callback", callback);
/* ... your code ... */
}
);
};
You can view the arrangeArgs proxy code in my GitHub repository here:
https://github.com/joelvh/Sysmo.js/blob/master/sysmo.js
Here is the utility function with some comments copied from the repository:
/*
****** Overview ******
*
* Strongly type a function's arguments to allow for any arguments to be optional.
*
* Other resources:
* http://ejohn.org/blog/javascript-method-overloading/
*
****** Example implementation ******
*
* //all args are optional... will display overlay with default settings
* var displayOverlay = function() {
* return Sysmo.optionalArgs(arguments,
* String, [Number, false, 0], Function,
* function(message, timeout, callback) {
* var overlay = new Overlay(message);
* overlay.timeout = timeout;
* overlay.display({onDisplayed: callback});
* });
* }
*
****** Example function call ******
*
* //the window.alert() function is the callback, message and timeout are not defined.
* displayOverlay(alert);
*
* //displays the overlay after 500 miliseconds, then alerts... message is not defined.
* displayOverlay(500, alert);
*
****** Setup ******
*
* arguments = the original arguments to the function defined in your javascript API.
* config = describe the argument type
* - Class - specify the type (e.g. String, Number, Function, Array)
* - [Class/function, boolean, default] - pass an array where the first value is a class or a function...
* The "boolean" indicates if the first value should be treated as a function.
* The "default" is an optional default value to use instead of undefined.
*
*/
arrangeArgs: function (/* arguments, config1 [, config2] , callback */) {
//config format: [String, false, ''], [Number, false, 0], [Function, false, function(){}]
//config doesn't need a default value.
//config can also be classes instead of an array if not required and no default value.
var configs = Sysmo.makeArray(arguments),
values = Sysmo.makeArray(configs.shift()),
callback = configs.pop(),
args = [],
done = function() {
//add the proper number of arguments before adding remaining values
if (!args.length) {
args = Array(configs.length);
}
//fire callback with args and remaining values concatenated
return callback.apply(null, args.concat(values));
};
//if there are not values to process, just fire callback
if (!values.length) {
return done();
}
//loop through configs to create more easily readable objects
for (var i = 0; i < configs.length; i++) {
var config = configs[i];
//make sure there's a value
if (values.length) {
//type or validator function
var fn = config[0] || config,
//if config[1] is true, use fn as validator,
//otherwise create a validator from a closure to preserve fn for later use
validate = (config[1]) ? fn : function(value) {
return value.constructor === fn;
};
//see if arg value matches config
if (validate(values[0])) {
args.push(values.shift());
continue;
}
}
//add a default value if there is no value in the original args
//or if the type didn't match
args.push(config[2]);
}
return done();
}
I recommend you to use ArgueJS.
You can just type your function this way:
function getData(){
arguments = __({id: String, parameters: [Object], callback: [Function]})
// and now access your arguments by arguments.id,
// arguments.parameters and arguments.callback
}
I considered by your examples that you want your id parameter to be a string, right?
Now, getData is requiring a String id and is accepting the optionals Object parameters and Function callback. All the use cases you posted will work as expected.
So use the typeof operator to determine if the second parameter is an Array or function.
This can give some suggestions:
https://planetpdf.com/testing-for-object-types-in-javascript/
I am not certain if this is work or homework, so I don't want to give you the answer at the moment, but the typeof will help you determine it.
Are you saying you can have calls like these:
getData(id, parameters);
getData(id, callback)?
In this case you can't obviously rely on position and you have to rely on analysing the type:
getType() and then if necessary getTypeName()
Check if the parameter in question is an array or a function.
You can use the arguments object property inside the function.
I think you want to use typeof() here:
function f(id, parameters, callback) {
console.log(typeof(parameters)+" "+typeof(callback));
}
f("hi", {"a":"boo"}, f); //prints "object function"
f("hi", f, {"a":"boo"}); //prints "function object"
If your problem is only with function overloading (you need to check if 'parameters' parameter is 'parameters' and not 'callback'), i would recommend you don't bother about argument type and
use this approach. The idea is simple - use literal objects to combine your parameters:
function getData(id, opt){
var data = voodooMagic(id, opt.parameters);
if (opt.callback!=undefined)
opt.callback.call(data);
return data;
}
getData(5, {parameters: "1,2,3", callback:
function(){for (i=0;i<=1;i--)alert("FAIL!");}
});
This I guess may be self explanatory example:
function clickOn(elem /*bubble, cancelable*/) {
var bubble = (arguments.length > 1) ? arguments[1] : true;
var cancelable = (arguments.length == 3) ? arguments[2] : true;
var cle = document.createEvent("MouseEvent");
cle.initEvent("click", bubble, cancelable);
elem.dispatchEvent(cle);
}
Can you override the function? Will this not work:
function doSomething(id){}
function doSomething(id,parameters){}
function doSomething(id,parameters,callback){}

Categories

Resources