why are square brackets used in javascript function calls? jquery - javascript

From:
andrew whittakers example showing result numbers in a custom jquery autocomplete implementation
_response: function(contents){
$.ui.autocomplete.prototype._response.apply(this, arguments);
$(this.element).trigger("autocompletesearchcomplete", [contents]);
}
why [contents] and not contents ?

It's a requirement from jQuery's trigger function that the second parameter be an array (prior to 1.6.2), thus the wrapping to make it an array. From the trigger docs (emphasize by me):
$('#foo').bind('custom', function(event, param1, param2) {
alert(param1 + "\n" + param2);
});
$('#foo').trigger('custom', ['Custom', 'Event']);
The event object is always passed as the first parameter to an event
handler, but if additional parameters are specified during a
.trigger() call, these parameters will be passed along to the handler
as well. To pass more than one parameter, use an array as shown here.
As of jQuery 1.6.2, a single parameter can be passed without using an
array.
So as of 1.6.2, it's actually not necessary to wrap the single argument in an array.

If the function expects an array, then you put your one or more elements in square brackets. For example, trigger's function declaration is
.trigger( eventType [, extraParameters] )
Since you may want to give it more than one extra parameters, it accepts an array of them. If you have only one extra parameter to give, such as "contents" in your case, then you can put it into an array (or if you have just one parameter, you also can not put it into an array, as JQuery now accepts either way).

As Trinh pointed out its an array [content] with one element.
I dont know why but if you change it to content instead of [content] it will search for the query in the whole word.
If its [content] it will search only at the beginning.

Related

What do those numbers mean in the parenthesis after the function in javascript?

*Don't mind the jQuery syntax. It serves as an example only and not the focus of the question.
$('target').on('click',function(){
'do something'
},5);
What does the value of 5 do? Does it set an initial value? Can you have multiple values like:
},5,6,5);
or can you only have one value?
They are simply function parameters. There is nothing special about the 2nd parameter, which happens to be a function. For the sake of clarity you could also refactor the code to look like this:
$('target').on('click', doSomething, 5);
function doSomething(){
// do something
}
To see exactly what parameters you can pass to the .on() function I'd recommend reading the documentation.
This argument passes value to handler.
You can get value from event.data.
It must be single value.
If you want to pass multiple data, pass value by object.
$("button").on("click", 3, function(e) {
alert(e.data) // alert 3
});
Reference: http://api.jquery.com/on/

How jQuery distinguish between 'data' and 'selector' parameter?

in jQuery function:
.on(event, [selector,] [data,] handler)
How jQuery parse this call:
on('click', 'tag3', () => {})
tag3 is selector or data?
The last argument must be the handler. So if there are two arguments there there is no data and no selector.
If there are four arguments than the second one must be selector and the third one must be data.
So it only becomes tricky if there are exactly three arguments.
If the second argument isn't a string, then it can't be a selector, so it must be data.
If it is a string then it could be a selector or data. Now jQuery could do some heuristics by running it through the selector engine and seeing if it is a valid selector … but it doesn't. It just assumes that if the second argument is a string then it is a selector.
How jQuery distinguish between 'data' and 'selector' parameter?
They have a different data-types
data - is a plain object (not a DOM or jquery object)
selector - is a string or a jquery/DOM/DOM-array object.
so, jquery can make out whether an argument is a selector or data by judging the properties of the argument, for example this and this
return obj instanceof HTMLElement; //to check if it is a DOM object
or
return obj instanceof jQuery; //to check if it is a jquery object
tag3 is selector or data?
As per documentation
If a string is passed as the parameter to $(), jQuery examines the
string to see if it looks like HTML (i.e., it starts with ).
If not, the string is interpreted as a selector expression, as
explained above. But if the string appears to be an HTML snippet,
jQuery attempts to create new DOM elements as described by the HTML.
Then a jQuery object is created and returned that refers to these
elements.
If the string passed to jquery method is an HTML then subsequent object is either a document (DOM object) or an attributes object.

passing HTML element as an arguvment to a function vs. using getElementById to get same element

When defining a function how do you decide if the function will get HTML elements passed as an argument or use getElementById instead? Is one way faster than the other? I know that having things passed as an argument increases the re-usability but it's sometimes hard to for see whether function is going to be used in another piece of code.
Just to clarify instead of using getElementById I would have something like this <input type="text" name="colour" onkeyup="myFunction(this.value)" />
Functionally it doesn't make much difference if you call getElementById before you call the function, and pass the result, or from within the function. There is a modicum of extra flexibility by passing in an element to the function because you can then also use other selectors (besides just id) to find your element.
To be flexible, you can make functions that can take either:
function whatever( element ) {
if (typeof element === 'string')
element = document.getElementById( element );
// ... do stuff ...
}
Always pass the object, not the ID. Passing the object is like giving you a book. Passing an ID is showing you the name of a book, then putting the book back in the library and asking you to find it.
There's no reason to search for the element every time.

Passing an array in a single argument using jQuery deffered.resolveWith()

I have a jQuery deferred, which I an resolving like so:
deferredAction.resolve(returnArray);
and this is calling a callback like:
function someCallback(myArray) {
...
}
This works fine, the callback function receives the array. However I need to set the context of the callback function, so I used deferred.resolveWith like so:
deferredAction.resolveWith(someContext, returnArray);
The context is now being set correctly. However, it now seems as if the returnArray is being split up. My callback only receives the first item of the array.
Why is this happening, and how can I work around it?
The documentation states that you should pass the arguments in a single array. In your case:
deferredAction.resolveWith(someContext, [returnArray]);
I fixed this by putting square brackets around the return parameter:
deferredAction.resolveWith(someContext, [returnArray]);

JavaScript: Sending comma separated string of parameters to a javascript function

I am having a function in javascript as
function add(v1,v2){
var add=v1+v2;
}
Now I am calling this function as below -
write.out(var param="1,2";);
write.out(window[add](param););
Using the above call, it's not working. What it does is it gives the complete string "1,2" as value to the first param(v1) of the function.
Its working if I call the function in following way -
write.out(var param1="1";);
write.out(var param2="2";);
write.out(window[add](param1,param2););
I want to achieve it using the first way where i can send the parameters as a comma separated string of parameters.
Can some one help me out how this can be done...
Thanks!!!
You can make usage of ECMAscripts .apply(), which calls a function and accepts an array of paramters.
window['add'].apply(null, param.split(','));
That way, we execute the add function, setting its context to null (you could also change that if you need) and pass in the two paramters. Since we need an Array, we call split() on the string before.
So basically, the above line is the same as
add(1,2);
Since you're haveing that function in the global context (window), we don't even need to write it that explicitly.
add.apply(null, param.split(','));
will just be fine.

Categories