views:

24

answers:

1

I wasn't sure of the title, but I hope you will be able to help me.

I want to use kinda the same pattern that jQuery uses for their event handlers, like click/hover/blur etc, where you use this inside the event handler to get the object.

How do I accomplish this?

// The event handler
var handler = function() {
     alert(this); // how do I set "this" in the trigger?
}

// The function that triggers the event handler
var trigger = function(handler) {
     var o = someObject;
     if($.isFunction(handler)) handler(); // how do I set "o" as the this-reference in handler?
}
+2  A: 

You use the "call" or "apply" functions on the Function prototype:

 handler.call(thingThatShouldBeThis, arg, arg, arg);

or

 handler.apply(thingThatShouldBeThis, [arg, arg, arg]);

Call takes a list of arguments like a regular function, and apply wants the arguments in a single array.

Old versions of some browsers didn't have "apply", but I don't know whether that's worth worrying about now.

Pointy
got it, thanks!
Mickel