This is one reason why using Event Listeners instead of Event Handlers is so
much better. With an Event Listener, you wouldn't need to worry about any
other handlers. In addition, your code would ensure the handlers are all
called ... unless code that executes AFTER your code sets the onclick
handler in an unsafe way. Whereas with the Event Listener, the order
wouldn't matter.
I would urge you to consider moving to an Event Listener model. If you're
using any of the major frameworks, they all have great cross browser methods
for doing this. Alternatively, it's not difficult to roll your own addEvent
method. For example:
function addEvent( obj, type, fn ) {
if ( obj.attachEvent ) {
obj['e'+type+fn] = fn;
obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
obj.attachEvent( 'on'+type, obj[type+fn] );
} else
obj.addEventListener( type, fn, false );
}
function removeEvent( obj, type, fn ) {
if ( obj.detachEvent ) {
obj.detachEvent( 'on'+type, obj[type+fn] );
obj[type+fn] = null;
} else
obj.removeEventListener( type, fn, false );
}
source: h <http://ejohn.org/projects/flexible-javascript-events/>
ttp://ejohn.org/projects/flexible-javascript-events/<http://ejohn.org/projects/flexible-javascript-events/>
Hope that helps.
Peter Foti
On Wed, Dec 15, 2010 at 1:03 AM, Yu-Hsuan Lai <[email protected]> wrote:
> When I globally invoke a function, the this inside it will refer to window.
> I have read "Good Part" so I know to workaround it by another variable
> "that". But see below example:
>
> I want to append some code to an event handler:
>
> aDiv.onclick = function () {
> var tmpFunc = aDiv.onclick;
> return function () {
> tmpFunc();
> someAnotherFunc();
> }
> }();
>
> It almost works well. But if origin onclick contain a this, it will refer
> to window because tmpFunc() is a global invocation.
> I found a solution, but I think it's not clever:
> (If possible I wouldn't like to change origin onclick because it's in
> another file)
>
> aDiv.onclick = function () {
> var tmpFunc = aDiv.onclick;
> var tmpObject = aDiv;
> return function () {
> tmpFunc.apply(tmpObject);
> someAnotherFunc();
> }
> }();
> --
> Lai, Yu-Hsuan
>
> --
> To view archived discussions from the original JSMentors Mailman list:
> http://www.mail-archive.com/[email protected]/
>
> To search via a non-Google archive, visit here:
> http://www.mail-archive.com/[email protected]/
>
> To unsubscribe from this group, send email to
> [email protected]<jsmentors%[email protected]>
>
--
To view archived discussions from the original JSMentors Mailman list:
http://www.mail-archive.com/[email protected]/
To search via a non-Google archive, visit here:
http://www.mail-archive.com/[email protected]/
To unsubscribe from this group, send email to
[email protected]