Skip to content Skip to sidebar Skip to footer

How To Implement A Simple Prioritized Listener Pattern In JavaScript

I have an event/listener manager that has this function: var addListener = function(event, listener) { myListeners[event].push(listener); //assume this code works } But no

Solution 1:

maybe its a better way then mine.. but that is a specific way, i mean you have to insert new handlers in the block. This is a more generic tool, however it seems to have application on your case.

i suggest this:

//makes a closured function that calls this function after the other
Function.prototype.prefix=function(o) {
    var that=this;
    return function(){
        that.apply(this,arguments);
        return o.apply(this,arguments);
    };
}
//prefix=reversed sufix
Function.prototype.sufix=function(o) {return o.prefix(this);}

with this code you can append/prepend functions to each other to form a kind of chain, its usefull to add another listener or to track a functions usage, or even do adapt code with minimal impact.

some usage

function audit() {console.log(arguments.callee.caller,arguments.callee.name,arguments);}
function a() {alert(arguments);}
a=audit.prefix(a);


//a user function
function f() {alert(arguments);}
f("test");//just do the alert as defined
 f=audit.prefix(a);
f("test");//now arguments will be on console too

//a builtin function
//this audit example only write to the console the arguments being passed to it
function audit() {console.log(arguments.callee,arguments);}
//auditing alert function (not too usefull, but shows it works even for
alert=audit.prefix(alert);//alert is now prefixed with audit

//an event handler
document.body.onclick=function() {alert("clicked");};
document.body.onclick=audit.prefix(document.body.onclick);

Post a Comment for "How To Implement A Simple Prioritized Listener Pattern In JavaScript"