for (var key in obj[i]) {
dataDump[key] = textField.value;
var callback = function(zeKey){
return function(e){
dataDump[zeKey] = e.source.value;
};
}(key);
textField.addEventListener('change', callback);
}
When I load the window, this function gets called automatically, which I don't want and instead I want this to be called only when I do a change.
The main point is calling function(zeKey){...}(key). When you do so, key, which is a string is copied as a parameter (zeKey) to your anonymous function.
The following
var callback = function(zeKey){
return function(e){
dataDump[zeKey] = e.source.value;
};
}(key);
Calls the anonymous function with argument zeKey.
This anonymous function returns another function. This returned function is assigned to the callback.
If 1 what you mean by "the function is getting called" then this is expected behavior.
This entire code should be called only after DOM is ready. Place all these in a function and make sure the function is called only on window.onload or (jQuery's) .ready()
The function returned by the function will be called only during the callback.
Add these code once dom is created. If above code is inside a function, attach to window.load or write these code at the end of page.
Related
Playing around with the .on('click', ) event and I get differing behaviour based on whether I supply an anonymous vs named function (the named function doesn't work). Is this a syntax error?
<div id="myID"> abc </div>
<script>
$("#myID").on('click',function(e){
console.log(e.type);
}); //works
function handle(e){
console.log(e.type);
}
$("#myID").on('click',handle(e)); //doesn't work
</script>
You need to replace
$("#myID").on('click',handle(e));
with
$("#myID").on('click',handle);
When you call a function, it is executed immediately. This happens when you do
$("#myID").on('click',handle(e));
You call the function, passing an event e which does not exist yet. What you want instead is giving jQuery a function that it should call when the user clicks on the element with the id myID.
This is possible in JavaScript because it has first-class functions. This means that if you create a function like this:
function handle(e){
console.log(e.type);
}
then you get a reference to the function that you just created. This reference is stored in a variable named handle. You could achieve the same if you do:
var handle = function (e) { // create a function and store a reference to it in a variable
console.log(e.type);
};
The function takes an argument e. This doesn't exist yet, it has to exist in the moment you call the function:
handle(e); // ReferenceError: e is not defined
You can pass the reference to that function to jQuery, which then calls your function when the user clicks the element. At that point, e still doesn't exist, because it will contain information about the event, which hasn't occured yet. It will look like this:
$("#myID").on('click', handle); // pass a reference to the handle function to jQuery
Now, handle doesn't get called, because you only pass a reference to the function. You could say that you pass the function as an argument to another (jQuery) function. This is called a callback function.
Edit
Note that all functions that were created above take e as their argument. The argument doesn't have to exist in the very moment you create the function. However, when you (or jQuery) call the function, you have to provide an argument so that the function can do its job.
It's the same with an unnamed function: you create the function, but the argument does not exist yet. When you (or jQuery) call the function, you have to provide an argument.
This means there is no essential difference. The only difference is that one function has a name, the other one doesn't. You could even do this:
$("#myID").on('click', function handle (e) { // pass a reference to the function, but do not call it
console.log(e.type);
});
... which has the same effect as:
$("#myID").on('click', function (e) { // pass a reference to the function, but do not call it
console.log(e.type);
});
... except that in the first example, you keep a reference to the function that you created in a variable called "handle". In the second example, you lose the reference to the function, and only jQuery will be able to use your function.
Edit end
Another example for that would be:
var testFunction = function (arg) {
console.log('My argument is:', arg);
};
var executeTwoTimes = function (callback) { // accept a callback function as the first argument
callback('foo'); // execute the callback function
callback('foo');
};
executeTwoTimes(testFunction); // pass a reference to testFunction
// or:
executeTwoTimes(function (a) { // pass a reference to an anonymous function
console.log(a + ' bar');
});
I hope I could make things clearer for you.
When i was reading some code of jquery then i found this in one of their widgets
option: {
_page: this._getPage,
_panelInner: this._getPanelInner()
},
_getPage : function(){ //code goes here that returns something..},
_getPanelInner : function(){ //code goes here that returns something..}
I wanna know how's the first this._getPage function is being called without parenthesis. And if functions can be called like this then why the next function _getPanelInner is being called with parenthesis..?
_panelInner will hold the value returned by the _getPanelInner function while _page will hold a reference to the _getPage function. This means that the function would be able to be called in one of the following ways:
option._page()
this._getPage()
Both of these function calls would execute the same function but that function is not called automatically (according to the code that is displayed).
It's not getting called, it's only having a reference to the function so later you can do:
option._page();
I'm using an addEventListner method on a HTMLElement inside a function that is called on onLoad. However, the method gets executed even before i try the click event in the html page.
function setConfigurationMenu(){
var navConfigure = document.querySelector(".navConfigure");
var navBody = navConfigure.querySelector(".body");
var navTop = navConfigure.querySelector(".top");
navTop.addEventListener("click", alert("jow"));
}
So what's going on here, any ideas?
thx,
This is happening because you are executing the alert function and passing its return value (which is undefined) as parameter to the addEventListener method. You actually need to pass a function to it.
navTop.addEventListener("click", functionToBeTriggered);
As alert expects a parameter that is your text, you might want to wrap it into an anonymous function that calls it. For example:
navTop.addEventListener("click", function() {
alert("jow")
});
This happens because you pass function result instead of function handler, try anonymous function for this:
navTop.addEventListener("click", function() {
alert("jow");
});
In other words in your case you just invoke function, but you need to pass handler for this.
This function gets called on page load, not when .somebutton is clicked. I'm not sure why. I want to be able to pass the variables so that I may use this function in multiple places with different values. Thank you very much.
var i = "this be i";
var u = "this be u";
function dosomething (var1, var2){
console.log(var1 + " and " + var2);
}
$(".somebutton").click(dosomething(i,u));
You are passing value returned by dosomething(i,u) to click handler. This is why it ise executing without clicking, it is happening as soon as you call your function (that is: dosomething(i,u)). You need to wrap your function call inside anonymous function:
$(".somebutton").click(function() { dosomething(i,u); } );
You can only pass a function by reference using the method in your example (ie. without parameters). The reason your function works on load is because it is immediately invoked due to the trailing () brackets.
If you need to pass parameters you need to wrap it in an anonymous function, like this:
// on click:
$(".somebutton").click(function() {
dosomething(i, u);
});
// on page load:
dosomething(i, u);
In JavaScript doing
$(".somebutton").click(dosomething(i,u));
will not assign the function to your click event, but will rather call the function and assign whatever result the function returns. You need to reference your function instead :
$(".somebutton").click(dosomething);
If you need to pass variables to your function, then you need to wrap the said function inside another anonymous one :
$(".somebutton").click(function() { dosomething(i, u); });
I have a javascript which I didn't write but I need to use it ..
function function1()
... body..
and at the end
I have this
'callback': 'getListCallback'
}
What does this callback mean and getListCallback = function(obj) is another function, does this mean that results from function1 are returned to function getListCallback?
Tnx
A callback function is a function that is going to be called later, usually when some event occurs. For example, when adding an event listener:
function callback(){
alert("click");
}
document.body.addEventListener("click", callback, true);
In many cases you pass the callback function as an anonymous function:
setTimeout(function(){alert("It's been 1 second");}, 1000);
The code getListCallback = function1(obj); will not call getListCallback with the results of function1(obj). It will store whatever function1(obj) returns into getListCallback. If function1 returns a function, then you can call that function later, like so:
function function1(obj){
return function(){
alert("getListCallback was called. obj = "+obj);
}
}
getListCallback = function1(1);
getListCallback();
Yes, it should mean that
normally a callback function means a function which will call after current function execution finished.
This
getListCallback = function(obj){// do something} is like assigning this "function(obj){//....}" to a variable which can use in any place where you need to use that function.