On Mon, Mar 28, 2011 at 8:53 AM, Mark McDonnell <[email protected]> wrote:

> I've uploaded a copy of my script here: https://gist.github.com/890700 (copy
> of the script is also listed below)


Just the link to the gist is all that's needed - the code you posted to the
list got mangled anyway. And let's skip the 432KB screenshots too. :-) If a
screenshot helps illustrate your problem, upload it somewhere and post a
link.

So back to your code... Is it a requirement that your library API follow the
DOM event listener model where you pass a reference to the original callback
function when you detach an event listener? That was a really poor design
decision in the DOM APIs, and unless you *must* follow that model, you can
do better.

Simply have your add() function create and return an object. Save a
reference to the original event listener in the object, and give the object
a .remove() method. That method then has a reference to the original
callback which it can use to call the appropriate DOM remove method.

In skeletal form:

    // Using the API
    var listener = add( element, 'click', function() {
        alert( 'click' );
    });
    // ...
    listener.remove();

    // Implementing the API
    function add( element, event, callback ) {
        var listener = {
            callback: callback,
            remove: function() {
                // pass listener.callback to the DOM remove function here
            }
        };
        // add DOM event listener here
    }

This is much simpler and more efficient than having to keep a list of
listener functions so you can find them later. And it makes your API easier
to use too: now you can freely use anonymous functions for your event
listeners and still be able to remove them later.

-Mike

-- 
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]

Reply via email to