Dojo.hitch immediately-called: Confirming my suspicions - javascript

This is probably a quick one. From what I understand, the dojo.hitch() function is useful for giving you a function callback that will always be called in the namespace you need (the first argument). However, I've seen a number of calling syntaxes like the following:
dojo.hitch(iamanamespace, iamanamespace.doSomething)();
The part that weirds me out is the two parentheses at the end. They're apparently not creating this function for later - they're just calling it right now. My obvious thought is that this could be shortened to:
iamanamespace.doSomething();
I was just sort of doing this replacement absent-mindedly, thinking it was the result of someone being over-careful with this references, but then I found that I was able to locate a few instances of this in the "dojox" modules, and even one inside of dojo/_base/lang that did change the namespace context, but still could have just used ".call()".
Can I just confirm with anyone who's used dojo for a while what situation, if any, might demand the use of a hitch to be called immediately, as opposed to doing it the normal, old-fashioned way?

I haven't used Dojo, but from looking at the source I can tell you that you're right. When you know the arguments, you should shorten the call.
There might be one reason only to use hitch though: If you want to allow both functions and method names it might be shorter to immediately-invoke a hitched function than to write something like
if (typeof fn == "string")
fn = (context || global)[fn];
if (typof fn == "function")
fn.call(context);
else
throw "not a function";

Related

What purpose does makeEmptyFunction serve in fbjs?

I was looking through the React source and stumbled across a requirement with var emptyFunction = require('fbjs/lib/emptyFunction');.
I looked at this function and was confused by what it does.
Here is the function
function makeEmptyFunction<T>(arg: T): (...args: Array<any>) => T {
return function() {
return arg;
};
}
const emptyFunction: (...args: Array<any>) => void = function() {};
In the comments, they give the following explanation which I was confused by:
This function accepts and discards inputs; it has no side effects.
This is primarily useful idiomatically for overridable function
endpoints which always need to be callable, since JS lacks a null-call
idiom ala Cocoa
I have never come across null call idiom and was hoping someone could clarify what this means and explain the purpose of this function in less technical language.
Hopefully this question will not get looked down on because it isn't exactly code related. Maybe it belongs somewhere else, if so I'm sorry.
When programming in JavaScript, we can take a function as a parameter to a certain operation. As an example, a function may have a callback which is invoked after some kind of event.
function doIt(callback) {
// some work
callback();
// more work
}
Now if this callback is an optional parameter and it's not provided, we will get Uncaught TypeError: callback is not a function error because callback is undefined. There are two solutions to this issue. The obvious one is checking the callback with an if statement. Another option is set an empty function as the default value of callback if it's not assigned. This approach is very useful and shines if we have multiple places which invoke the callback function. So we don't need to check it for undefined every time before calling it.
function doIt(callback) {
callback = callback || function(){};
// some work
callback();
// more work
}
Likewise, there are lots of use cases where we can have overridable functions variables. It's a common pattern to set these type of variables to empty function as the default value so that we can call them without worrying about whether those are assigned/overridden or not.
Also, in some special cases, it's useful to have functions which do nothing but return a particular value. makeEmptyFunction is used for creating such functions. Basically, it returns a function which does nothing but returns what ever the parameter pass to it.
emptyFunction.thatReturnsFalse = makeEmptyFunction(false);
As you can see in the file, above code generate an empty function which returns false value.
"null call idiom" is something we find in Objective-C/Cocoa programming. It basically allows you to call a method of an uninitialized object (null pointer) without giving any errors like in most of the other languages. I think that's what the author have tried to explain in the comment.
Since JavaScript doesn't have such language feature, we explicitly achieve it using empty functions. Some people call it no-op or noop and you can find similar helpers in other popular JavaScript libraries such as JQuery and AngularJS also.

How can I ensure that all of my JavaScript functions return a value?

I've had numerous bugs happening just because of a missing return in a function. You see, when most of the code you write is in Ruby, it's easy to forget about explicit returns.
So I'd like to use something similar to JSlint (which I already use) to check that all functions return something. Yes, I think it's better to explicitly return something when it's not required than to hunt down missing returns.
So, are there any tools that would check for returns? Or maybe I can assert it in runtime in a simple manner?
Please don't suggest Coffeescript, I'm aware of its existence.
JSUnit example:
<script language="javascript" src="jsUnitCore.js"></script>
<script language="javascript">
function testWithValidArgs() {
assertEquals("someFunction should return something", "Expected REturn Value", someFunction(2, 3));
}
</script>
Just add return consistently. But to be honest, JSlint is a VERY strict checking tool. You will never get errors if you're not returning values unless you're trying to define a variable using the response of a function, but in that case it's more than logic that you add a return statement.
However, if you're still dedicated to have a return statement in every function, you should add them from the start. There is no tool that adds them.
I'm not aware of any tools that will do this out of the box. But it would not be hard to write one.
Start by using UglifyJS to parse your code into a syntax tree. Write a recursive function that examines all code, looking for function definitions. For every function you find, look at the last statement. If that one is not a return-statement, then print a warning.
(Too long for comment.)
My problem with returning something when a function has no (meaningful) return value is that it's misleading, unless it returns undefined, which defeats the purpose.
If I see a return, I have to reason about the code both in the method and at the call site.
In the function I have to determine if it ever returns anything else, why it returns the value it does, etc. The only real way around this is to return a constant that makes it obvious the it's not really returning anything, it's just to satisfy a desire to return something.
At the call site, if a return value is ignored, I need to understand why, and if it's okay to do so. If I know every function returns something, I then have to check the function to see if it's returning that special value, or go through the above process.
I'd almost rather namespace my functions into "function" and "method" namespaces at that point as a differentiater. This would allow automated testing of each namespace to make sure that all functions return something useful, all methods specifically don't, and would provide a source-level clue as to which the caller should expect.

Is it possible to access the DOM element 'this' in a non-function parameter argument in a jQuery plugin?

I have a potentially strange question about this and jQuery plugins
As I understand it, the following is a very basic jQuery plugin:
$.fn.clickclone = function(param){
return this.click(function(){
param.apply(this);
});
};
(pretending that's a plugin that somehow extends click().)
So, if I pass a function as an argument, it does what it needs to do and properly accesses this as a DOM node. Easy.
That's all clear to me.
What's not clear is, is there any way I could pass a non-function argument to the plugin and have it properly access this from the arguments? ie, could I configure the plugin to do something like this:
$("#foo").pluginname(["foo", $(this).text() ]);
Such that for:
Bar
It would properly pass an array to the plugin, with the second item in the array returning the value Bar?
I'm doing this, basically, to provide syntactic sugar for my plugin, where you can pass an array as a shortcut (in addition to using a normal callback function as the main functionality). Except, doing that, I lose access to use of this. Hence my dilemma.
EDIT: This is evil, but, it seems like one work around is to pass the argument as a string and then eval it. Not a workable solution for me, but, it illustrates what I'd like to be able to do:
$.fn.clickclone = function(param){
return this.click(function(){
if(typeof param === "function"){
param.apply(this);
}
else if(typeof param[1] === "string"){
console.dir("This is evil: " + eval(param[1]));
}
});
};
There's no general way to do this without a function, since, in the purely mathematical sense, you are asking for a function of the input (that is, a function of this): something that depends on this in a certain way.
You could perhaps hack it with strings, like so, but you lose the flexibility of functions:
$.fn.alertMe = function (methodToAlert) {
alert(this[methodToAlert]());
};
// usage:
$("#foo").alertMe("text");
$("#foo").alertMe("width");
And if you find using a function acceptable but the this syntax confusing, you can simply do the following:
$.fn.alertMe = function (alertGetter) {
alert(alertGetter($(this));
};
// usage:
$("#foo").alertMe(function (x$) { return x$.text(); });
$("#foo").alertMe(function (x$) { return x$.width(); });
And for completeness I guess I should mention you could probably get away with an eval-based solution, looking something like $("#foo").alertMe("$(this).text()"), but eval is evil and I will neither write up nor condone such a solution. EDIT: oh, I see you have done so in an edit to your original post. Good job corrupting future generations ;)

In javascript what does this syntax `(function(window,undfined)){}(window)` accomplish

I am trying to understand how to "chain" JavaScript events together like jQuery does. I found a question here on S.O. that was similar to my goal, but I do not understand the code in the answer.
Code Source
(function( window, undefined ) {
...etc...
}(window)
What does that mean? What is it doing? It reminds me of Jquery's $(document).ready(){} function, but I don't know why this person wrapped his code in this anonymous function that passes window and undefined.
My ultimate goal is to figure out how to execute methods on an object by chaining methods together like jQuery. I know that jQuery already does this but I am looking into this primarily for growth as a developer.
It defines a function (using a function operator as opposed to a function statement). The parenthesis around it ensure that it is treated as the operator rather than the statement.
It then executes it immediately, passing window as an argument.
Essentially, this is the same as:
var myFunction = function( window, undefined ) {
...etc...
};
myFunction(window);
… but without the interstitial variable.
This has nothing to do with jQuery style function chaining, where each method effectively ends with return this (so calling a method on the return value of another method is the same as calling it on the original object).
When a function is called with fewer arguments than its signature contains, the trailing arguments are assigned the value undefined.
So the above is a roundabout way of getting hold of the undefined value even if some lunatic has redefined it by saying var undefined= 'hello';. (This is illegal anyway in ECMAScript Fifth Edition's ‘strict mode’, but JavaScript coders do some weird things sometimes.)
There isn't really a good reason for passing in window like this though... the traditional way to get window if you can't rely on window is to call a function directly and use this.
Either way, this is simply defensive coding against pathological author JavaScript. It's not something you should worry about whilst writing your own code (in any case there's no way you can stop every way someone might mess up their JS environment), and it's nothing to do with chaining.

What real purpose does $.noop() serve in jQuery 1.4?

Pouring over the release notes regarding jQuery 1.4, I came acrosss $.noop() which is:
Description: An empty function. (added in 1.4)
You can use this empty function when you wish to pass around a function that will do nothing.
Perhaps I'm missing something profound here, but what exactly is a practical use of passing around an empty function?
Code examples appreciated.
This function was proposed due to performance issues on embedded systems when using $.ajax, reported on the jQuery-Dev mailing list. You can see the thread.
Basically, they preferred to introduce and use this single empty function, rather than declaring empty anonymous functions all around.
Now this function is internally used in the ajax, event and offset modules.
You can give a look to the commit when it was introduced also.
If you have a function that accepts a function as a parameter, and you don't have any code to give it, you can pass $.noop.
I can't think of any such cases in jQuery where the parameter isn't optional in the first place, though.
Unlike writing function(){}, passing $.noop will not create a new function instance, saving a bit of memory. However, if whatever you're passing it to modifies the function object (eg, funcParam.id = 2), passing $.noop will mess things up.
Real World Example (well almost):
jQuery.fn.myAwesomeAjax = function(url, complete) {
return jQuery.ajax(url || this.url)
.complete(complete || jQuery.noop);
};
Use it instead of function (){}
Probably if some bad API requires a function as a parameter, and you don't want to do anything in it, this would be a framework-supported way of making that obvious.
I use a couple of plugins which require callbacks, but for some parts I don't actually want to use a certain callback. So, I put in function() {}.
noop is defined in the jQuery source as
noop: function() {}
so it will fit anywhere you'd use a blank function, such as the above example.
The only logical reason is if you're calling a function that does something AND calls another function, and you want the higher-level function to do its thing without calling a parameter function.
Most of the jQuery functions optionally take a parameter function, so you don't have to pass one in. Maybe there's one or two where that's not the case -- or maybe it's to assist developers with their custom code that behaves like this.
If a function requires you pass a function as an argument maybe? It's shorter to say do_something($.noop) than do_something(function(){}).
Although not by much...
...6 characters...
...yeah, that feature looks quite useless actually.
It can be useful if you have a function that supplies functions to other functions.
Example: You have a List of data. Each item has a Button that does something. The "something" can be different for every item. You have a "FunctionFactory" that takes in the item and returns a function. If you don't want the button to do something for whatever reason, then the cleanest way could be to return an empty function, as that way you know that your Factory ALWAYS returns a function.
I don't have a concrete example for jQuery, but I guess this could come in handy when used in an .each or .map block.
It's purely a convenience/replacement for function(){} in the context of where callbacks are required - I don't think I'll be using it anytime soon.
I bet the jQuery team had quite a laugh when they dropped it in though, also serves a comedic purpose.

Categories

Resources