Avoid Adding Event Multiple Times

前端 未结 2 840
日久生厌
日久生厌 2021-01-04 09:27

I am dynamically adding events using addEvent(\"keydown\", function() {}); to an element. My problem is that there are times when this code get\'s run on the sa

2条回答
  •  离开以前
    2021-01-04 09:59

    Maybe your problem is not where or when to add event handler, but how to add. It is possible to delegate events to parent element. For example, this is a classic way of adding an event handler directly to the target element.

    new Element( 'p', { 'text': 'Some Text' } ).inject( $( 'container' ) );
    
    $$( '#container p' ).addEvent( 'click', function() {
        console.log( this );            
    });
    
    new Element( 'p', { 'text': 'Some Text' } ).inject( $( 'container' ) );
    

    And, of course, only the first paragraph has click event.

    And below is an example of event delegation.

    $( 'container' ).addEvent( 'click:relay(p)', function() {
        console.log( this );            
    });             
    
    $( 'container' ).adopt([
        new Element( 'p', { 'text': 'Some Text' } ),
        new Element( 'p', { 'text': 'Some Text' } )
    ]); 
    

    Since event listener is assigned to a parent for all of its children, all paragraphs will have the click event, no matter when and where they are created. It is very useful when you are adding elements into the page dynamically.

    I do not know how much this helps, but it's good to know.

    Element.Delegation

提交回复
热议问题