I have a script, that based upon specific scenarios, may need to supersede functions to do some processing before eventually calling the original function. (See "'overriding' Javascript Function")
I can get this working in general - here's a basic example using the jQuery plugin Tinyscrollbar (not my intended application, just something quick and easy to illustrate):
(function ($) {
// Snip..
function initalize() {
oSelf.update();
setEvents();
return oSelf;
}
// Snip..
function setEvents() {
(function () {
var oldInit = wheel;
wheel = function (oEvent) {
console.log('Intercept');
oldInit(oEvent);
}
})();
// Original event code, irrelevant to question
}
function wheel(oEvent) {
// Actual function, related to using the mousewheel
}
})(jQuery);
When I scroll the mousewheel, the console prints 'Intercept', and the scrollbar moves as originally defined. Wonderful!
However, the function name is hardcoded, and doesn't live in the global scope, so window[] is unavailable (which I like). Is there any possible combination of black magic, 'new Function()', and/or other way to loop through a potential list of function names (which may change based on other logic) and encapsulate them in this (or similar-in-spirit) manner?
Thanks in advance!
Unfortunately, there's no way to enumerate or dynamically access members in a scope object (with the convenient exception of the global scope/window object)
So you'd need to rephrase your code a bit. Instead of having free-floating functions in your outer function, have objects with methods on them. That'd make replacing those methods much easier.
There's some additional trickiness if you modify your functions after you started assigning them as event handlers or whatever. If you happen to use some kind of bind() wrapper around those functions, the correctness of your behavior will depend a lot on that bind() function.
Specifically, if you want the replacement method to retroactively become the method called for any event handler or callback it was assigned to, you'll want to use a bind() wrapper that takes a context object and a string meant to be the function name rather than a context object and a function reference. (and make sure that bind() doesn't resolve that string early to shave some ms on each calls.)
If don't don't want the retroactive behavior, you still have to make sure you don't have some bind()-ed version of the original method floating around and still being used for new callbacks after your replacement happened.
Related
I am learning JavaScript and becoming confused by the logic of the code examples. From codecademy. Why are there function set-ups in function calls?
I'm quite confused. I am moving from a simplified C-like langue.
The JavaScript example
var main = function(){
$('.article').click(function(){
$('.description').hide();
$(this).children('.description').show();
});
};
My understanding:
- main is a function name with a return type of var.
$('.article') is a element/object/or class object.
.click() is a call to a member function
But:
???:
.click(function(){
$('.description').hide();
$(this).children('.description').show();
});
This seems to be a newly on the spot created function to run When/If click() is activated or run.
The way I used to think is like this:
var *p_obj = $('.article');
var *p_obj = $('.description');
var do_click()
{
p_obj2.hide();
p_obj.children(p_obj2).show();
}
var main(){
p_obj.click(do_click);
}
Function main() looks at p_obj and calls click().
Click() evaluates to true/false and run the pointer_to function do_click().
Function do_click() looks at the p_obj2 and calls hide(), which performs an action of hiding the p_obj2.
Function do_click() also looks at p_obj and uses children to scope focus to p_obj2, then it runs show(), which preforms an action of displaying p_obj2.
I do realize my C-like example is wrong and odd. I realize my terminology is wrong or otherwise used incorrectly.
The way this design looks seems like I must write extended functionality on-the-spot for every call to .click(), so if-then .click() is run on 3 different items, I'm creating different extended functionality for each object. But I would normally create a single function that varies it's internal execution based on the object or condition click() calls it by.
This set-up seems alright if the code a relatively simple or short, but on-the-spot functional seems like overworking for longer code and code where the functionality repeats but the objects change.
Am I thinking about JavaScript functions with-in functions correctly and is this a design goal of the langue to add long repeating extended functions with-in functions?
Here, you should understand 2 things:
passing functions as arguments
anonymous functions
The first concept is particulary important because callbacks are popular in JavaScript, so let me explain it for callbacks. Imagine we have 2 functions getStuffFromWeb and processStuff. You probably expect that they are used like this:
var result = getStuffFromWeb();
processStuff(result);
But the issue here is waiting for getStuffFromWeb may take some time (the server is busy), so instead they are usually used in a "when you finish, call this function" manner, which is:
var getStuffFromWeb = function(params,callback) {
...
callback(result);
};
getStuffFromWeb(someParams,processStuff);
Well, in fact the structure of getStuffFromWeb will be different, most likely something like this:
var getStuffFromWeb = function(params,callback) {
requestObject.make_request(params)
.onSuccess(callback);
};
So when getStuffFromWeb is called, it starts to listen to response while the code after getStuffFromWeb(someParams,processStuff); goes on evaluating. When the response comes, it calls the callback function to process the data further using the procedure we have defined (processStuff).
The second concept is rather simple: you may of'course write smth like
var processStuff = function() {...};
var getStuffFromWeb = function(params,callback) {
requestObject.make_request(params)
.onSuccess(callback);
};
getStuffFromWeb(someParams,processStuff);
but if you use processStuff only once, why define a named function? Instead, you can just put the very same expression inside the onSuccess param like this:
var getStuffFromWeb = function(params) {
requestObject.make_request(params)
.onSuccess(function() {...});
};
getStuffFromWeb(someParams);
This looks exactly like if we took the value of processStuff and put it directly to the onSuccess's argument (and that's called anonymous function). And also we got rid of an extra argument of getStuffFromWeb.
So basically that's it.
Simple answer is that the second argument of click() requires a callback function.
This can be a named function passed as reference as in your p_obj.click(do_click); example or it can be an anonymous function with self contained logic. Anonymous functions are very common in javascript
It's the same thing just with 2 different ways of declaring the callback.
Note that the only time you would return anything from an event handler function would be to return false which effectively prevents the default browser event (url opening from href or form submit for examples) and stops event propagating up the DOM tree
main is a function name with a return type of var.
No. main is a variable which is assigned an anonymous function. The function name would go between the keyword function and the () containing the argument list.
It has no return statement so it returns undefined.
$('.article') is a element/object/or class object.
It is a call to the function $ with one argument. The return value is a jQuery object.
.click() is a call to a member function
Pretty much. In JavaScript we call any function that is the value of a property of an object as method.
This seems to be a newly on the spot created function
function () { } is a function expression. It creates a function, exactly like the one used to assign a value to main earlier. This question is worth reading for more on the subject.
When/If click() is activated or run.
The click function is called immediately. The new function is passed as an argument.
The purpose of the click function is to bind a click event handler so that when a click event hits the element later on, it will trigger the function passed as an argument.
I do realize my c -like example is wrong and odd. I realize my terminology is wrong or otherwise used incorrectly.
Leaving aside vagaries of syntax. The main difference here is that the click event handler function is that the event handler function is stored in an intermediary variable.
You can do that in JavaScript just as easily, and then reuse the function elsewhere in the code.
var main = function(){
function show_specific_description() {
$('.description').hide();
$(this).children('.description').show();
}
$('.article').click(show_specific_description);
show_specific_description.call($(".article").last()[0]);
};
main();
is this a design goal of the langue to add long repeating extended functions with-in functions?
No. Passing a function expression as an argument is a convenient way to be more concise when you don't want to reuse the function. It's not the only way to pass functions about.
main is currently a function.
It is possible to be overwritten (even to a different type). var is not the return type, it's a statement that main is a variable.
All values should be declared as variables, within the highest scope you intend them to be used (in JS, scope typically means functions, not blocks).
You have the right idea, suspecting that the function gets passed in, and called at a later point in time (and this is actually one of the harder parts for people to get, coming from certain other languages). You'll see this behaviour all through JS.
One key thing to keep in mind in this language (you haven't hit it yet, but you will) is that JS is lexically scoped.
function getInnerX () {
var x = 5;
function getX () {
return x;
};
return getX;
}
var x = 10;
var getX = getInnerX();
console.log(getX()); // 5
The function getX inside of getInnerX has access to the references around it, at the point where it's defined (not where it's called), and thus has live access to the inner x, even if its value changes over time.
This will be another important piece of understanding what you see going on in the language, especially in the case of callbacks.
Reading Principles of writing consistent, idiomatic JavaScript in the section titled "Faces of this" it suggests that aliasing this in JavaScript is "extremely bug prone".
I personally try to use _.bind() (or something similar) whenever possible but does anyone know why aliasing this is so error prone?
There are four meanings this can take dependending on how it was invoked. Accordingly care must be taken to keep track of which this is being used, and I can think of this-prone problems in at least 3/4 of them.
Invoked as method
In obj.myFunc(), this binds to obj.
This one can be scary if myFunc is passed in a callback, as it will forget that it was once part of an object and be invoked standalone. See e.g. What does 'var that = this;' mean in JavaScript? for the usual workaround to this.
Invoked as standalone function
In plain myFunc(), this binds to global object.
Invoked as constructor
Invoked as new myFunc() (very different! All functions that are intended to be invoked with new should be capitalized, thereby looking like a pseudoclass). Creates a new object, binds it to this and (probably) returns that object.
Of course if you drop the new you will bind to the global object, which will likely clobber a lot of stuff and leave your program in a very broken state. The capitalization convention is very important, and lets this problem be picked up by JSLint (IIRC).
Invoked with apply (or call)
Invoked as myFunc.apply(obj, args), in which this binds to obj. Note this has security implications even, as any caller can swap out this with its own spoofed object.
this being aliases everywhere would be bug prone because it gets rather difficult (for the developer) to remember exactly what this is referring to in a given situation. This can easily lead to a developer using this believing it refers to one element, when in reality it is something totally different. For example:
$('#something').click ( function (e) {
//this refers to the clicked element
var _this = this; //Tracking a reference to the clicked element `this`
$.each(someArray, function(index, value) {
//this refers to the current element being iterated in someArray
$.ajax({
url : 'some/path',
success: function (res) {
//this refers to the ajax request
//_this still references the clicked element
}
})
})
})
Furthermore, if you need to access one this from within the scope of another this (for instance this clicked element from within the ajax call) you have to keep a reference to it somehow. I have marked this in the code.
I have a situation like this one:
talenti = $(".talenti");
filtra = $(".filtra");
wrapNavHeight = $("#wrapNav").outerHeight(true);
filtra.click(function(e) {
e.preventDefault();
$(".nasco").hide();
$("#sliding-navigation").delay(delay).show();
delay += 500;
talenti.removeClass('opened');
filtra.addClass('opened');
filtra.attr('id',"focF");
talenti.attr('id',"");
if (filtra.hasClass("opened")) {
$("#wrapNav").slideToggle("100", "linear", function(){
alert(wrapNavHeight);
$("#container").animate({"height": "+=wrapNavHeight"}, 100,function(){
$(".box").animate({"top": "+=wrapNavHeight"});
});
});
}
});
I am trying to get wrapNavHeight but alert(wrapNavHeight); outputs null; can't then assign that value to the next animate lines
Anyone?
isn't it just that you are assigning the variable the value of outerHeight at the time it's not visible? I think you need to re-evaluate outerHeight after the toggle transition. Replace
alert(wrapNavHeight);
with
alert($("#wrapNav").outerHeight(true));
see if that's any better?
Nobody else actually explained why this happens. Here's why:
It depends on:
which object is used as "this" for invocation of the function containing all the code above
which object is used as "this" for invocation of the function defined starting on line 4 of your code
In JavaScript, "global" references actually apply to the current this object (or to the "true" global object (window in web browsers) if not within a function)
Thus, if the this objects for the 2 functions I pointed out above are different, then you'll get the situation you observed.
In the browser, the default this object is usually window, but this can be changed when the function is run, such as by passing a different parameter to apply or by calling the function as a method.
Been a year since I used jQuery seriously, but if I recall right, jQuery event handlers usually rebind this to something useful related to the event (using apply-- you can do this too).
So, assuming the outer function's this hasn't been bound to anything special other than window, simply replace wrapNavHeight with window.wrapNavHeight in the inner function to achieve your desired effect.
(In practice I wouldn't actually do this, though, as a matter of style. Just declare wrapNavHeight as a var within the outer function instead, and then you'll get lexical scoping.)
Try searching.
jQuery global variable best practice & options?
I've been dipping my toes into Javascript and now looking at the following piece of code:
var router = new(journey.Router)({
...
});
router.root.bind(function (res) { res.send("Welcome") });
Question: What is the root function above bound to? What does this binding do?
I understand that 'bind()' is supposed to bind the execution of a function to a specified object as a context. I do not understand how a function/method can be bound to an other function. All of the references I have looked at are talking about binding to an object.
'root' is a getter method defined in journey.js (at line 145) as
get root() {
return this.get('/');
},
which is simply an expedient shorthand for
get('/')
And in this context, the call to bind will associate the provided callback function with the route defined as root, such that any requests that match the root path ('/') will be answered by the string 'Welcome'.
UPDATED
Upon further examination of the journey.js source, it appears the use of bind() in this context is not an example of currying at all.
Rather this particular bind() is defined as a function of the object returned by route() (which in turn is called by get()) in journey.js at line 131, and is simply used to set (or bind) the handler for a particular route.
IMPORTANT: This call to bind() IS NOT the same as Function.prototype.bind().
I'm leaving my previous answer below because I believe the information regarding currying still has value in this situation.
This use of Function.prototype.bind() is called 'currying' and is used to provide a new function which has values already provided for one or more of its expected arguments.
A simple example of currying would be if you assume:
function addSome(amount, value) {
return value + amount;
}
which could be curried to produce a new function:
var addOne=addSome.bind(1);
and is exactly the same as:
function addOne(value) {
return addSome(1,value);
}
Currying is a feature from [functional programming].
See [bind - MDN Docs] for an explanation of bind() and [currying] for a formal definition of this technique.
[functional programming]:http://en.wikipedia.org/wiki/Functional_programming
[bind - MDN Docs]:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind
[currying]:http://en.wikipedia.org/wiki/Currying
Not totally familiar with the object that you're using, but it's using javascript "anonymous functions" to create an object that contains a chunk of code so it can be passed around like a variable. It can later be called by appending the () onto the end.
See: http://helephant.com/2008/08/23/javascript-anonymous-functions/
Probably the most common use of this sort of thing is for setting a callback function, that is, when you call a function on router, when that function completes, it will finish by calling whatever you bound to it in the first place.
Say I'm using a generic javascript library (such as colorbox) to pop up a dialog on the screen and prompt the user for information. Once that gets done, or if the user closes the box without entering anything, I want the box to do something custom. I don't want to have to dig around in colorbox's source code to do this, so they allow places for all sort of callback functions. Say when the users enters the information and hits a button, it'll close the colorbox, submit ajax, and refresh the underlying page.
I am learning javascript and jquery and wondered whether it is good or bad practice to nest all my functions within $(document).ready(function). Is there any difference between this:
function someFunction()
{
return someThing;
}
$(document).ready(function()
{
// some code
...
someFunction();
});
and this:
$(document).ready(function()
{
// some code
...
function someFunction()
{
return someThing;
}
someFunction();
});
Be gentle - I'm pretty new to this!
You forgot at least one :-)
function someFunction()
{
return someThing;
}
$(someFunction);
Generally there is no difference between: $(document).ready(argFunc) and $(argFunc).
The other variations you listed have all different scopes for different things.
For example, in your 2nd block you declare someFunction inside a non-global scope, while your first and my example declare it in the global scope, which has implications for reachability.
Also, technically, with both of your variations you produce one extraneous function call. Because in this case, all you call is one function (which you can also write like my example).
UPDATE1:
To add some additional info and to further the discussion about scopes - JavaScript has very loose requirements for existence of variables. If it doesn't find them in the current scope, it wall just traverse the call chain upwards and look for it - until it finds it or not. That is why you can access the jQuery object ($) from anywhere.
There is however this:
someFunction($) {
// You can use $ here like always
return someThing;
}
$(someFunction);
This means, that the handlers (there can be more than one) for the document ready event of jQuery get passed jQuery itself as an argument.
If you specify this parameter for your function, you'll use that one, if you reference it. Otherwise, you are using the global one. That reduces the length of the upward look-up - chain.
That is completely irrelevant from a performance stand point.
But, by specifying this as a parameter, you make it absolutely clear where the jQuery object is coming from. Even that might be irrelevant.
I just wanted to show, that these callback-type functions in jQuery often take parameters that are useful.
So if you are ever stuck and need access to some object you don't have, it might be worthwhile to check the jQuery docs to see, if there is not a parameter, that does what you want.
To conclude this update, I very much like the first comment to the question, which is a much better answer than mine.
UPDATE2:
On the point of multiple callbacks for document ready (or any event binder in jQuery for that matter):
You can do this:
$(func1); // or $(document).ready(func1);
$(func2); // or $(document).ready(func2);
Both will get called as soon as jQuery fires its document ready event. That might come in handy depending on the perspective. Some would say, it encourages spreading your logic around. Others might say, it allows for cleaner separation of all the things that need to be done on document ready.
yes. The first way puts someFunction in the global scope so that it can be called by anyone. If you intend this function to be "private" and only callable by some code then the 2nd way is preferred. Generally you should prefer the 2nd way unless you need to export the function into global scope.
The differences are subtle, but worth bringing up.
Declared functions outside of DOM ready:
If you don't call the functions until DOM ready, then this is more efficient since it is registering the functions before waiting for the DOM to load (Edit: As is noted in the comments, there will be a slight performance penalty in accessing global variables due to scope resolution). This is very minor and probably not noticeable.
More importantly, you functions become globals, and you can clutter the global scope if you're not namespacing properly:
var myFuncs = {
someFunction : function() { ... },
someOtherFunciton : function() { ... }
};
Declared inside DOM ready:
Functions are no longer globals, but your functions are registered along with your other DOM ready code.
I would say it's fine to go either way in most cases, but definitely declare your functions under one namespace.
First off, functions are typically only declared if they are going to be used more than once. If you put a function inside the $(document).ready(function) then it won't be available outside the scope of the $(document).ready(function). Check out an article on Javascript Scope.
This is because $(document).ready accepts a function as a parameter and in your two examples you are declaring an inline function (that's the function () {} code in there). Check out a discussion of inline functions vs parameterized functions.
So, it boils down to deciding if you are going to use someFunction() more than once. If so, put it outside the $(document).ready function. Otherwise, you don't really need a function since you are just calling it once.
As long as someFunction() does not try to manipulate the dom, there is no difference. $(document).ready is called after all elements in the dom have loaded and can be accessed with javascript. If you try to manipulate an item in that page with javascript before it loads, it wont be there and the code will break.