Adding and Removing Event Listeners with parameters

后端 未结 4 413
我在风中等你
我在风中等你 2020-12-09 18:31

I am writing a vanilla JavaScript tool, that when enabled adds event listeners to each of the elements passed into it.

I would like to do something

4条回答
  •  借酒劲吻你
    2020-12-09 18:49

    This can be done quite easily, just not as you have it right now.

    Instead of trying to add and remove random anonymouse functions, you need to add or remove a function that handles the execution of your other functions.

    var
        // Here we are going to save references to our events to execute
        cache = {},
    
        // Create a unique string to mark our elements with
        expando = String( Math.random() ).split( '.' )[ 1 ],
    
        // Global unique ID; we use this to keep track of what events to fire on what elements
        guid = 1,
    
        // The function to add or remove. We use this to handler all of other 
        handler = function ( event ) {
    
            // Grab the list of functions to fire
            var handlers = ( cache[ this[ expando ] ] && cache[ this[ expando ] ][ event.type ] ) || false;
    
            // Make sure the list of functions we have is valid
            if ( !handlers || !handlers.length ) {
                return;
            }
    
            // Iterate over our individual handlers and call them as we go. Make sure we remeber to pass in the event Object
            handlers.forEach( function ( handler ) {
                handler.call( this, event );
            });
    
        },
    
        // If we want to add an event to an element, we use this function
        add = function ( element, type, fn ) {
    
            // We test if an element already has a guid assigned
            if ( !element[ expando ] ) {
                element[ expando ] = guid++;
            }
    
            // Grab the guid number
            var id = element[ expando ];
    
            // Make sure the element exists in our global cache
            cache[ id ] = cache[ id ] || {};
    
            // Grab the Array that we are going to store our handles in
            var handlers = cache[id ][ type ] = cache[ id ][ type ] || [];
    
           // Make sure the handle that was passed in is actually a function
            if ( typeof fn === 'function' ) {
                handlers.push( fn );
            }
    
            // Bind our master handler function to the element
            element.addEventListener( type, handler, false );
    
        };
    
    // Add a click event to the body element
    add( document.body, 'click', function ( event ) {
        console.log( 1 );
    });
    

    This is just a cut down version of what I've written before, but you can get the gist of it I hope.

提交回复
热议问题