Is it possible to bind a function to another function on invoke? So for example, it would go something like this:
function a(){...}
function b(){...}
b.bind("onInvoke","a");
So when b is called, a is also automatically called.
EDIT: OK OK, to clarify, this is not a question on chaining. The idea is to find an elegant way to do event binding. Observe the normal "non-elegant" way with normal function call-back:
function handler(){...}
function caller1(){handler(); ...}
function caller2(){handler(); ...}
function caller2(){handler(); ...}
// More callers all over your website everywhere else
That works right? But what if I have caller all over the place? It's hard to organize or change things.
Now observe the superior solution! (If one exist)
function handler(){...}
// Caller make no reference to handler on creation
function caller1(){...}
function caller2(){...}
function caller3(){...}
// Caller function are still all over the place, all over your website
// Event handler registered later in one location here, doesn't matter where they are phsically
caller1.bind("onInvoke",handler);
caller2.bind("onInvoke",handler);
caller3.bind("onInvoke",handler);
So very much like your normal HTML - JQuery event registration. You don't write onClick on every image the user might click on (which are all over the place), it would be way too troublesome to organize that! You just write one simple
$("img").bind("onClick",click_handler);
for your entire site. This is the jist of what I am looking for, except for JS functions.
I hope that clarify things.
EDIT 2: Need to work with IE7!!! JavaScript 1.8.5 is great and everything, but nothing support it right now.
Invoking a JavaScript FunctionThe code inside a function is executed when the function is invoked. It is common to use the term "call a function" instead of "invoke a function". It is also common to say "call upon a function", "start a function", or "execute a function".
What is an Event ? JavaScript's interaction with HTML is handled through events that occur when the user or the browser manipulates a page. When the page loads, it is called an event. When the user clicks a button, that click too is an event.
An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined.
You can drop the == true since they both return booleans. If this condition if (function1() && function2() ){ is true, it means that these functions was executed and returned true. just be aware of that if the first function doesn't return true or the second won't be executed.
You can do that with an aspect-oriented approach. Here is a simple example:
Attach call to a() to function b():
var _b = b;
b = function(){
_b();
a();
}
Now call b():
b();
See it in action here: http://jsfiddle.net/eZ9wJ/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With