Skip navigation

How to bind multiple functions to an event?

You can bind two functions to an event. Let us consider the code below

window.onload = firstFn;
window.onload = secondFn;
function firstFn(){var myFirstFunction;}
function secondFn(){var mySecondFunction;}

Shock: You can’t bind two functions to window.onload event like above. The second function overrides the first one. Now onload only binded with secondFn function.

How to do it correctly? Here it is

fol = function(){var myFirstFunction;};
sol = function(){var mySecondFunction;};
col = function(){fol(); sol();};
window.onload = col;

Define a new function and call two function inside the definition of newly created function. Assign new function to onload event. If you don’t know already any function is binded with onload, here comes the solution

Basically you need to chain like this

var sol = function(){var mySecondFunction;};
if(window.onload){
    var fol = window.onload;
    var col = function(){fol();sol();};
    window.onload = col;
} else {
    window.onload = sol;
}

If you are working in a team environment, you might not know wheather other developers already binded any functions on a particular event. So this technique may be useful.

Here comes most compact version (thanks to ppk)

var old = (window.onload) ? window.onload : function () {};
window.onload = function () {old(); sol()};

First you define a variable old. If the window currently has an onload event handler, put this event handler in old, if it hasn’t, put an empty function in old. Second line isobvious.

Hope this helps you people. 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: