issue with multiple window onload - javascript

I luckily found this code on the net for continuos add on onload from a different subject completely
function myPluginLoadEvent(func) {
// assign any pre-defined functions on 'window.onload' to a variable
var oldOnLoad = window.onload;
// if there is not any function hooked to it
if (typeof window.onload != 'function') {
// you can hook your function with it
window.onload = func
} else { // someone already hooked a function
window.onload = function () {
// call the function hooked already
oldOnLoad();
// call your awesome function
func();
}
}
}
// pass the function you want to call at 'window.onload', in the function defined above
myPluginLoadEvent(func);
However, this only allow for one add on onload call. How do I loop this for multiple on load call such as for i, 1++ ?
Many thanks in advance.

The code you posted will work repeatedly. Each time it's called, oldOnLoad contains whatever was previously assigned to window.onload, which could be the result of a previous use. So it just keeps chaining all the functions.
However, the modern approach is to use addEventListener rather than assigning to window.onload.
window.addEventListener("load", func);

Related

Add event listener of a method present in another js file

I am accessing few methods written in another js file. So i'm accessing them like this:
file1:
function minit() {
this.addval = function(val1, val2) {
return val1 + val2;
}
function autoexecute(d) {
//do something here//
//raise event//
}
};
file2:
var con = new minit();
var result = con.addval(2, 3);
/*
con.autoexecute(function(d) { //Wanna do something like this
alert(d);
});
*/
Above things are working as expected, getting result..
Now, Suppose autoexecute(d) method is invoking automatically after a time interval. How can i know if the method is executed ?
So that, I want to create an event(in file2) of autoexecute(d)(in file1).
UPDATE:
I hope this example will help you to understand the issue..
company.js //this is the main file which will be used as a reference in ui.html
function hello(personname) { //this method will invoke automatically after 1 minute..
}
ui.html
<script src="company.js"></script>
<script>
$(document).ready(function() {
function bye(personame) { //this method will be called automatically if hello method invoked.... personame is the argument passed from hello method//
alert("comany.js -> hello function is executed");
}
});
</script>
You can only do this if the functions have the same scope (global scope is the best case scenario). If the autoexecute function has local scope then you cannot to do it.
In essence, override the original function like this...
// keep a reference to the original function
var _autoexecute = autoexecute;
// override the original function with your new one
function autoexecute(d) {
alert("before autoexecute"); // fired before the original autoexecute
_autoexecute(d); // call the original autoexecute function
alert("after autoexecute"); // fired after the original autoexecute
}
Now, whenever autotexecute is called it will call your new function which can handle both before and after events, as well as calling the original function. Just remove the (horrible) alerts and replace with event handlers as required.
To my knowledge, and someone should correct me if I am wrong, there is no way (at least without some library) to detect a function being fired in javascript. Function executions do not fire an event that other functions can 'handle' in that that sense.
In your example you wanted a function to automatically fire after the other function has fired, all you need to do is call the function you want to fire at the end of the one that was "fired" in the first place. Confusing but hope this helps.
function handler(){
alert("main function was fired!");
}
function main(){
//Code of main goes here and then at the end just add:
handler();
}
Now when your "main" has finished its work it will call upon the handler function.
Regardless of where you define the handler function, which can be a different file or same file, so long as it is reachable from within the main's scope, it will be fired at the end of it. It can even be declared after main has been declared, so long as it is declared before main is fired.

Explain this JavaScript onload function

Here's an example for registering a function on document load (most of it taken from JavaScript: The Definitive Guide):
"use strict";
//run function f when document is loaded
function onLoad(f) {
if (onLoad.loaded) // If already loaded
window.setTimeout(f, 0);
else if (window.addEventListener)
window.addEventListener("load", f, false);
}
onLoad.loaded = false;
onLoad(function() { onLoad.loaded = true; });
onLoad(myfunc);
function myfunc() {
console.log("Hello, world!");
}
I'm getting confused with the line onLoad(function() { onLoad.loaded = true; });. I can tell that it's self-invocation, but using the function name again baffles me. Why is it needed? I find that if I do only (function() { onLoad.loaded = true; }); then also the output is the same.
Finally, I can get the same output by using:
function myfunc() {
console.log("Hello, world!");
}
window.onload = (function() {window.setTimeout(myfunc, 0);});
How is my code better/worse?
Thanks in advance!
I'm getting confused with the line onLoad(function() { onLoad.loaded = true; });. I can tell that it's self-invocation, but using the function name again baffles me.
It isn't a self-invocation.
It is a call to the function onLoad (previously defined) with one argument (which is a function expression).
Finally, I can get the same output by using… How is my code better/worse?
Your code will:
Only support a function function to be called when the load event fires. If you try to assign another function, it will overwrite the previous one instead of setting up two functions to be called when the event fires.
Won't call the function immediately (or at all) if the load event has already fired (so you can't use it in a script that can be dynamically added to the page as well as being used normally)

javascript passing event in closure

I was trying the following:
f.addEventListener('submit',(function(frm){
var func = (function(e){somefunction(e,frm);})(e);
})(f),false);
But this is failing. I want to pass the form (f) as a static reference and the dynamic event object to the named function 'somefunction'.
What I have above isnt working, what is the right syntax for passing both?
The issue is that each of the functions is being called right away, with undefined actually being passed to addEventListener().
You'll want to instead return one of the functions without its calling parenthesis so the event can call it later:
f.addEventListener('submit', (function (frm) {
return function (e) {
someFunction(e, frm);
};
})(f), false);
Though, with event bindings, you may not necessarily need the closure, as the <form> will be the context (this) of the function passed:
f.addEventListener('submit', someFunction, false);
function someFunction(e) {
var frm = this;
// ...
}
not saure exactly what you are trying to do but, to looks like you are trying to manually pass in the form via the event handler. Instead save a reference and just refer to it in the handler such as
f.addEventListener('submit',function(){
var func = function(e){
somefunction(e,f);
};
},false);
you shouldn't need the self executing functions unless I am missing your intent here

How to retrieve the function called in an onload?

Is there a way for me to retrieve and change the value of an onload function?
i.e
i want to get the value of the onload on this tag:
<body onLoad="test();">
is there a way for me to do this?
since i need to change the function being called on certain circumstances.
Yes, you can get it from window.onload.
var func = window.onload;
Given your example, you'll get a function that looks something like this:
var func = function(event) {
test();
};
So then you can call your function whenever you need, though you won't have an event object to pass it.
func();
To change it, just do it sometime before the onload event happens:
<body onload="test();">
<script>
var func = window.onload;
alert(func); // alerts the function
if (condition_is_met) {
window.onload = function() {
/* my new func */
};
}
</script>
</body>
This will overwrite the original function with a new one. As long as you do it before the event occurs, your new function will be invoked.

Calling a function in javascript object literal notation declaration

I'm trying to call a function within an object literal that I created, using the this keyword. But an error shows up saying this.doTheMove() is not a function:
window.onload = function(){
var animBtn = document.getElementById('startAnim');
animBtn.addEventListener('click', Animation.init, false);
}
var Animation = {
init: function(){
this.doTheMove(); // I'm calling the function here, but it gives an error.
},
doTheMove: function(){
alert('Animation!');
}
}
Why is there an error?
An explanation of what's happening. Pointy's answer is good but I want to explain it more generically. A very good research on this can be found here
An event handler is just a callback. You pass it a function and an event to listen on. Interally all it will do is call that function.
Animation.init is just a getter for that function. Think of it like this:
var callback = Animation.init
animBtn.addEventListener('click', callback, false);
...
// internal browser event handler
handler() {
// internal handler does stuff
...
// Oh click event happened. Let's call that callback
callback();
}
So all you've done is passed in
var callback = function(){
this.doTheMove(); // I'm calling the function here, but it gives an error.
}
By default in javascript this === window. This will refer to the global object if it isn't set to something. The net effect is that window.doTheMove is called. And that function doesn't exist.
In this case since callback is actaully called by an event handler the this object points at the DOM object that triggered the event so your calling node.doTheMove which still doesn't exist.
What you wanted to do is wrap it with a reference to Animation.
var callback = function() {
Animation.init();
}
This is a function execution and it executes init on Animation. When you execute it on an object like that then internally this === Animation as you would expect.
To sum up. The issue here is that Animation.init is just a reference to a function. It has no information about anything else like Pointy mentioned.
You have to change the way you set that up:
window.onload = function(){
var animBtn = document.getElementById('startAnim');
animBtn.addEventListener('click', function() { Animation.init(); }, false);
}
In JavaScript, the fact that a function happens to be defined as part of an object literal really doesn't mean very much (if anything, in fact). The reference to Animation.init does get you to the proper function, but the problem is that when the function is later invoked (in response to an actual "click"), the browser calls the function but has no idea that the object "Animation" should be the this reference. Again, the fact that the function was declared as part of the object is of no importance at all here. Therefore, if you want this to be something in particular of your own choosing, then you have to make sure it's set explicitly in code you control. The solution above is about the simplest way to do it: it handles the "click" events with an anonymous function that does nothing other than invoke the "init" function via an explicit reference through "Animation". That will ensure that this refers to the "Animation" object when "init" runs.
Another alternative would be to use the ".bind()" facility that some browsers and frameworks support:
window.onload = function(){
var animBtn = document.getElementById('startAnim');
animBtn.addEventListener('click', Animation.init.bind(Animation); }, false);
}
The net effect is almost exactly the same: that call to ".bind()" returns a function that invokes the function on which it was called (that being the "init" function in the "Animation" object), and does so with its first argument as the this reference (the "context" object). That's the same thing that we get from the first example, or effectively the same anyway.
Here's another nice approach, I think.
window.onload = function(){
var animBtn = document.getElementById('startAnim');
animBtn.addEventListener('click', Animation.init, false);
};
var Animation = {
init: function(){
Animation.doTheMove(); // This will work, but your IDE may complain...
},
doTheMove: function(){
alert('Animation!');
}
};
You might want to use the portotype base approach:
// generate a prototype object which can be instantiated
var Animation = function() { this.doTheMove(); }
Animation.prototype.doTheMove = function() {
// if the object has only one method, the whole code could be moved to
// var Animation = function() {...} above
alert('Animation!');
}
Animation.prototype.otherMethod = function(param1, param2) {
// ...
}
// run the code onload
window.onload = function(){
var animBtn = document.getElementById('startAnim');
animBtn.addEventListener('click', new Animation(), false);
}
Six and a half years later, but I'm hoping my answer can also provide some insight for current and future developers.
I tend to code using literal objects inside of self defined functions, and the original question posted works just fine if another self-executing function is added along with a try and catch statement.
It's very important to point out that it's all about scope and context.
Please correct any drawbacks or provide more effective suggestions of using this method.
(function() {
console.log(this); // window object
var animation = {
init: function() {
this.doTheMove();
},
doTheMove: function() {
alert("Animation");
console.log(animation); // animation object
}
};
(function() {
try {
console.log("animation.init"); // animation.init function
animation.init();
} catch(e) {
console.log("Error is: " + e);
}
})();
})();

Categories

Resources