what does jQuery(function) do - javascript

I am reading javascript web application and the author is using following code:
mod.load = function(func){
$($.proxy(func, this));
};
Can someone help me to understand why returning function from jQuery.proxy is inside jQuery wrapper.
Is this the same as:
mod.load = function(func){
var temp = $.proxy(func, this);
temp();
};

They are not the same but they have the same effect. Your second example executes the returned function directly while jQuery(function) binds it to the onload like $(document).ready(). mod.load probably is the onload however, so this makes no difference.
See http://api.jquery.com/jQuery/#jQuery3

Calling $() with a function argument is equivalent to applying $(document).ready() to that function: it waits for the DOM to be ready before calling it.
Therefore, in your second example, temp() may be called before the DOM is ready, depending on the moment when mod.load() itself runs.

Is the same, is just a shorthand.

Related

How can you pass anonymous functions as parameters to existing functions to use later in javascript?

I am trying to create a basic javascript framework that you can pass different things into, including functions for it to execute later. Right now, I'm in a more simple testing phase, but I can't quite get the function calling to work. A piece of my code is here:
[My JS Fiddle][1]http://jsfiddle.net/mp243wm6/
My code has an object that holds different data, and I want to call the method later, but with data that is available at the time of creation. Here is a code snippet of the function that uses the function that is passed to the object:
clickMe : function() {
this.obj.click(function() {
this.func();
});
}
Any suggestions or things I should read are welcome.
The problem is that there're two different contexts:
clickMe : function() {
// here is one
this.obj.click(function() {
// here is another
this.func();
});
}
You can simple pass the function as parameter, like the following:
clickMe : function() {
this.obj.click($.proxy(this.func, this));
}
http://jsfiddle.net/mp243wm6/2/
The problem:
Considering your code in the JSFiddle, you have:
onClick : function() {
this.obj.click(function() {
this.func();
});
},
As noted, you have different contexts going on here.
Consider the snippet this.obj.click(function() { this.func(); }). The first this here is a reference to the framework.events object. The second this here is a reference to whatever will be this when this function get called. In the case of your JSFiddle, when this.func gets called, this is actually the DOM object that represents the <div id="test">TEST</div> node. Since it doesn't have a func function, calling func() on it causes:
Uncaught TypeError: undefined is not a function
You have to understand the following: you have to pass the correct this in which you want the function func to be called.
The solution:
A couple of ways to make it work as you would like:
1. with bind
this.obj.click(this.func.bind(this));
This way, you are telling: "call my this.func function, but make sure that it will be called using the this that I am passing as a parameter". Vanilla JS, no $.proxy stuff.
JSFiddle
2. with a copy of the reference to the actual function
onClick : function() {
var theFunctionReference = this.func;
this.obj.click(function() {
theFunctionReference();
});
},
This way, you will not rely on the value of this outside of the context of the framework.events object.
JSFiddle
The issue is that this is not bound to the correct object. I would suggest you look into Function.bind() because that creates a function with this pointing to the right thing.

different ways to execute javascript code?

I see
First
$(function() {
...
});
Second
(function() {
})();
Third
function() {
}
$(document).ready(function(){
});
Maybe there are more, what are the differences?
Your notation is mainly jQuery (atleast the ones with $)
This is shorthand for a DOM ready function, equivalent to the bottom one
This is a self executing function with the parameter specified in the trailing ()
This is a DOM ready function $(document).ready(function() {}); atleast, the function above it is simply a function.
so these indeed are a few different ways to execute javascript code, some of them are library dependent (using jQuery) others are done specifically because of differences in scope.
the first block:
$(function() {
...
});
is utilizing the js library jQuery that uses the namespace '$' what you are doing here is calling the jQuery '$' function passing in the first parameter of another anonymous function... this is a shorthand way to call $(document).ready(function(){});... both of those statements wait for the DOM to complete loading (via the onload event) before interpreting the javascript inside
the second block:
(function() {
})();
is a procedure called an (IIFE) Immediately-Invoked Function Expression... which in essense is defining an anonymous function and calling it immediately.
the third block:
function() {
}
$(document).ready(function(){
});
represents two things... the first function declared actually should have been named something like function myFunction(){...} and thus could be called later myFunction(parameters);
and finally $(document).ready(function(){}); is the javascript library jQuery's way of saying grab the 'document' element of the dom, and attach an event listen to it looking for the onload event, when that event is triggered execution the function passed as a parameter...

Get jquery selector from object parameter

box_tpv1 = {
box:$("#box_tpv1"),
open:function(mensaje,f_ok,f_x){
this.box.show()
}
}
And when I call this box_tpv1.open() won't work, but If I write inside open function $("#box_tpv1").show() it works.
In your case, box_tpv1 is a singleton object, which cannot be further instantiated using new. Which means the value of this is insignificant.
You might as well simply call box_tpv1.box.show() inside the open function.
there might be issues on the context this function is being called and that depends upon from where are you calling this function from
try calling like this
box_tpv1.open.call(box_tpv1);
I don't know why but I solved it this way, I can get with this.box the value inside the object methods but doesnt work the jquery selector, if I do that it works
box_tpv1 = {
box:"#box_tpv1",
open:function(mensaje,f_ok,f_x){
$(this.box).show()
}
}

why the function call does not work this way?

This is the script that i tested when the page loads.
window.onload = initAll;
function initAll() {
document.getElementById("pTag").innerHTML = "Hello Java Script !";
}
The above script works fine till i put parenthesis like initAll() during the call. _( window.onload=initAll(); )_ . Nothing happens if use initAll() during function call. It is like the script wasn't there.
Why is it so ?
window.onload expects the value you set for it to be a function (functions are like any other object in JavaScript).
If you put parens after initAll, you actually invoke the function and set window.onload to the function's return value. Since the function does not return anything explicitly, this value is undefined. So in practice you can think of this code:
window.onload = initAll();
function initAll() {
// do something with document
}
as equivalent to this code:
var result = initAll();
window.onload = result;
function initAll() {
return null;
}
I 'm sure you can immediately see why this would not work.
Because you should not execute the function at that line, you should assign an event handler to the window object, which will be triggered/executed once the load event has fired, not the returned value of a function.
However, assigning an event handler window.onload is not recommended, because it will allow for only one handler to be attached. Consider using addEventListener.
Because you're not calling the function directly in the window.onload statement, but you're assigning a function to the onload event. The system will then automatically call your initall function when the event happens. Thats why you need the function itself (without parenthesis), and not the call (with parenthesis)
This has to do with the way Javascript works. Functions also are actually objects, like about everything in javascript.
So basically, you are assigning the "Object" initAll , which happens to be a function, to window.onload . This object is then called when the onload event is triggered, assuming it is a function.
Now, when you are putting parenthesis behind your objects name, you are basically telling it to treat that object like a function and call it. this is not the way how to assign it to a property, like the window.onload property.
window.onload = initAll;
You're binding the initAll function to the onload event of the window object. The function becomes the load handler. Now, when the load event fires at the window object, this function will be invoked.
window.onload = initAll();
You're immediately invoking the function initAll. this invocation returns undefined (in your case), and that undefined value will be assigned to window.onload. Assigning the undefined value to onevent properties obviously has no effect.
When you omit the parentheses in this call:
window.onload = initAll;
You are assigning to the window.onload event the reference value of the function initAll(). This causes the function to execute when the onload event is called because they share the same reference point. When you use the assignment like this:
window.onload = initAll();
You are assigning to the window.onload event the returned value of the function, which in this case is null.

Javascript scope help

I am relatively new to javascript so please be patient if what i am asking is completely stupid!
I am trying to make a simple module. Inside the module i want to have a config object that holds settings for the module. I am also using jquery. The jquery selectors work only when in a function directly in the main object/module.
I understand that javascript has functional scope so I am suprised that I cannot use the jquery selectors anywhere inside the module.
EDIT:
I want to be able to directly set all of my configs inside the configs object using jquery selectors. This way i keep all the messy stuff inside one place and can then access configs.whatever throughout the rest of the module. At the moment jquery selectors do not work inside the configs module.
var OB = function() {
var configs = {
'mode' : 'test',
'numOfSelects' : $('.mySelect').find('select').length, // This doesnt work
}
var getMode = function() {
return configs.mode;
}
function init() {
alert(configs.numOfSelects); // This alerts 0 until the following line
alert($('.mySelect').find('select').length); // This correctly alerts 2
};
var handlers = {
successHandler : function() {
alert("Success");
},
errorHandler : function() {
alert("error");
}
}
return {
init : init,
getMode : getMode
}
}( );
$(document).ready(function(){
OB.init();
});
It isn't that jQuery isn't in scope — that's that the code isn't executing when you think it is. The variable config is defined when that anonymous function (var OB = function() {}()) is executed. The DOM isn't ready yet, so that DOM traversal doesn't find anything. When you do the DOM traversal in init(), that isn't executed until it's explicitly called inside the $(document).ready() handler, at which point that DOM is set up. That's the difference you're seeing.
OB() needs to be called after the DOM has completely loaded. Hence the answer by Marcelo, which calls OB() in the ready() method.
EDIT: It's funny that my original answer below was incorrect because I didn't notice two little parentheses at the end of the definition of OB, and it turns out that these are the culprit. You define and then immediately invoke OB, which is before the DOM has been fully loaded. Remove those parentheses and make the change I suggest below.
Calling OB() returns an object with init and getMode, but you haven't called OB(), you've only referred to OB. Try this instead:
$(document).ready(function(){
OB().init();
});
Also, I assume you want to later refer to getMode. In particular, you will to get the copy of getMode that has access to the same local scope that your init() call had access to. To achieve this, you will need to store the result of calling OB() for later use:
var ob;
$(document).ready(function(){
ob = OB();
ob.init();
});
function some_other_function() {
... ob.getMode() ...;
}

Categories

Resources