I'm trying to update some old code someone left before, at some point, it made a call to the attr function of an old 3.3.1 JQuery like this:
$("#myiframe").attr("src", url, function () {
$(window).on("unload", function () {
// Some function stuff
});
});
My problem is than I want to know what exactly this does (I already know what attr does when it has 2 parameters, but not 3) before adapt it to a newer version, but when I search about the .attr function in JQuery, all I found is with only two parameters, not 3 like this, I don't know if is properly a callback function (unlikely, because none of the parameters this function accepts is a callback function), or other thing.
The JQuery file is the one served by googleapis, so is not likely it has been specially modified for this.
Please, can someone explain me what it does?
No signature of attr() accepts 3 arguments. The last argument is redundant. Even if it did serve a purpose, putting a window.unload event handler in there would not do anything useful.
Regards your comment under the question:
Why doesn't it launch a fatal error for the number of arguments?
It's because JS is a very permissive language. You can pass as many arguments to a function as you like, JS will ignore any extras and only bind those which you defined in the function definition (up to 2 in this case using attr()). Although note that it's still possible to retrieve all arguments that were used in the function invocation using the arguments keyword
Related
I was wondering about how functions work in javascript, I noticed in some cases, things like array.sort, array.filter, and event listeners the code that calls (not declares) the function (not using functionless or inline), usually FunctionName have parenthesis with the arguments in there (FunctionName(arg1, arg2, arg3...)). Are parameters “automatically” passed into the function?
Now I understand, looking wikipedia's article on callback looking at the alert, it looks like it first calls "calculate" first, supplies the 2 numbers and the function (that function name only, without the open and then closing parenthesis), and THEN uses the parameters for callbackFunction. So without the parenthesis on the function name is like without using bracket on an array name.
I had a doubt about replacing some characters in a textbox using jQuery and I landed in this question. The accepted answer suggested something like this:
$("#mySelector").val(function(i, v) { //i, v... where they come from??
return v.replace("#","Custom Text");
});
That works fine but I still have the same doubt. Those parameters, i and v. Where do they come from and how they are filled with data? They are not declared anywhere. How do i and v in this case, has the data that I need?
These answers talk about it, but it seems just an overcomplicated explanation for what should be, an easy thing to explain.
So, the question is simple. How in the world those parameters in the anonymous function, get filled with data. Where do they come from if I didn't declare them anywhere?
They are set when the jQuery library calls the callback. Note that you are passing a function as a parameter into the $.val function. The $.val function passes values to the function that you passed to it.
Here is a simple example of how callbacks work:
function coolFunction(callback) { // accepting callback
// extra processing here
callback(1, 2); // calling the callback
}
coolFunction(function(a, b) { // passing function as callback
console.log('annonymous', a, b);
});
The jQuery function val checks the argument passed into it. When it finds a function, it calls it for every element contained in the selector, where i is the index of the element in selector, and v is the value... ie the element's value.
I would like to know the difference between 2 implementations of callback functions.
This:
$("#button").on('click', function () {
//do something
});
Versus having the function already defined.
$("#button").on('click', btnFunction);
function btnFunction() {
//do something
}
Are there any implications with one compared to another? Performance-wise is one faster?
The first uses an anonymous function and the second does not. There's no difference in both.
See:
Why do you need to invoke an anonymous function on the same line?
Some folks prefer the second form because it gives a function name when using the debugger and tracing, but there are ways to get the same functionality in the first form.
If you are attaching and removing the event handler based on changing conditions, the second form is much easier to maintain, however.
There's no difference at all, and there's no performance issue with neither one of them. The only difference is that in one of them you're defining the callback function as an anonymous function, this way you cannot reuse it.
The other way, where you define it else where and named it and then pass it as a callback, you're defining a function that you can later reuse in another part of your code.
For example: if you want to do something when the document is ready, and then do se exact same thing when some one press a button you can use something like this:
function getData() {
//do something
}
$(function() {
// Call the function once the DOM is ready
getData();
});
// Call the same function when the button is clicked
$("#refresh_button").on('click', getData);
In most cases the first one will be used, called Anonymous Functions
The second one will be used when the function is not only used inlined here, but also needs to be reused somewhere else.
But anyway it could be a personal preference.
The only real difference you could see is that stack trace (if an exception is thrown for example) will be better, i.e. easier to debug, when using the second one.
Just reuse-ability.
In the second case, you could call btnFunction() somewhere else if need be.
Excuse me first. because i don't know this is question is valid or not. i if any one clear my doubt then i am happy.
Basically : what is the different between calling a method like:
object.methodname();
$('#element').methodname();
calling both way is working, but what is the different between, in which criteria make first and second type of methods. is it available in the core javascript as well?
In case if i have a function is it possible to make 2 type of method call always?
Can any one give some good reference to understand correctly?
Thanks in advance.
The first syntax:
object.methodName();
Says to call a function, methodName(), that is defined as a property of object.
The second syntax:
$('#element').methodname();
Says to call a function called $() which (in order for this to work) must return an object and then call methodname() on that returned object.
You said that "calling both way is working," - so presumably you've got some code something like this:
var myObject = $('#element');
myObject.methodname();
This concept of storing the result of the $() function in a variable is commonly called "caching" the jQuery object, and is more efficient if you plan to call a lot of methods on that object because every time you call the jQuery $() function it creates another jQuery object.
"Is it available in the core javascript as well?" Yes, if you implement functions that return objects. That is, JS supports this (it would have to, since jQuery is just a JS library) but it doesn't happen automatically, you have to write appropriate function code. For example:
function getObject() {
return {
myMethod1 : function() { alert("myMethod1"); return this; },
myMethod2 : function() { alert("myMethod2"); return this; }
};
}
getObject().myMethod1().myMethod2();
In my opinion explaining this concept in more depth is beyond the scope of a Stack Overflow answer - you need to read some JavaScript tutorials. MDN's Working With Objects article is a good place to start once you have learned the JS fundamentals (it could be argued that working with objects is a JS fundamental, but obviously I mean even more fundamental stuff than that).
The difference is very subtle.
object.methodname();
This is when JavaScript has the object at hand.
$('#element').methodname();
If you are using jQuery, you are asking jQuery to select the object that has the id of #element. After that you invoke the method on the selected object.
Could someone write down a very simple basic example in javascript to conceptualize (and hopefully make me understand) how the jQuery plugin design pattern is done and how it works?
I'm not interested in how creating plugin for jQuery (so no jQuery code here at all).
I'm interested in a simple explanation (maybe with a bit of Javascript code) to explain how it is done the plugin concept.
Plz do not reply me to go and read jQuery code, I tried, but I it's too complex, otherwise I would have not post a question here.
Thanks!
jQuery has a library of functions stored in an internal object named fn. These are the ones that you can call on every jQuery object.
When you do $("div.someClass") you get a jQuery object containing all <div> elements of that class. Now you can do $("div.someClass").each( someFunction ) to apply someFunction to each of them. This means, that each() is one of the functions stored in fn (a built-in one in this case).
If you extend (add to) the internal fn object, then you automatically make available your custom function to the same syntax. Lets assume you have a function that logs all elements to the console, called log(). You could append this function to $.fn, and then use it as $("div.someClass").log().
Every function appended to the fn object will be called in such a way that inside the function body, the this keyword will point to the jQuery object you've used.
Common practice is to return this at the end of the custom function, so that method chaining does not break: $("div.someClass").log().each( someFunction ).
There are several ways to append functions to the $.fn object, some safer than others. A pretty safe one is to do:
jQuery.fn.extend({
foo: function() {
this.each( function() { console.log(this.tagName); } );
return this;
}
})
Tomalak already posted almost everything You need to know.
There is one last thing that helps jQuery do the trick with the this keyword.
it's amethod called apply()
var somefunction=function(){
alert(this.text);
}
var anObject={text:"hello"};
somefunction.apply(anObject);
//alert "hello" will happen
It really helps in creating abstractions so that framework/plugin users would just use this as intuition tells them, whatever there is inside Your code
It works, as many other js frameworks, using javascript prototype orientation.
For instance you can declare a simple function
var alertHelloWorld = function() {
alert('hello world');
}
And then tie it to an existing object (including DOM nodes)
document.doMyAlert = alertHelloWorld;
If you do this
document.doMyAlert();
The alertHelloWorld function will be executed
You can read more about javascript object prototyping here