Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery-Intellisense for passed Arguments

How can i achieve that I get jQuery-Intellisense in the following code example?

function doSomething($jQueryObject) {
    $jQueryObject.   // I want to have Intellisense here
};

var $parameter = jQuery('body');
doSomething($parameter);

The problem is that Intellisense doesn't know that the parameter for the function is a jQuery-Object. How could I tell the function the parameter type?

I know I could write in the function something like

$obj = $j($jQueryObject);

to create a new jQuery-Objekt, but I would like to know if there is another way to solve this.

like image 441
iappwebdev Avatar asked Oct 10 '22 06:10

iappwebdev


1 Answers

Javascript is a loosely typed language which means the type is not declared explicitely, but decided internally at runtime.

Interllisense cannot determine the type of the variables (whatever the editor) because it is simply not defined. You can pass whatever you want to your doSomething() method. This is a powerful and flexible way of programming. The bad side is that it might require implementing some checks to avoid errors/exceptions

If you are building some sort of framework or API for other developers to use, you should consider testing the parameters' type.

To test a jQuery typed variable, do this:

var $obj = $jQueryObject instanceof jQuery
              ? $jQueryObject
              : $($jQueryObject);

Note: prefixing the variable name with $ is a good indicator of the jQuery nature of the expected variable for the developer using the function.

Edit: replaced typeof === "jQuery" by instanceof jQuery

like image 73
Didier Ghys Avatar answered Oct 21 '22 13:10

Didier Ghys