Search code examples
javascriptbackbone.jsbackbone-events

How to manually trigger a backbone click event without actually clicking


I have a backbone event handlers set up like this:

events : {
          "click .filter-options-container" : "filterOptionContainerClick",
    },

For one of these .filter-options-container elements, there is a scenario in which I want to trigger the filterOptionContainerClick function without actually clicking. The problem is that function needs access to event.currentTarget - so I can't just call the function - I have to simulate that click event. How do I do this? Here's that function:

filterOptionContainerClick: function(e){

      if (this.filtersEnabled){
        $(e.currentTarget).addClass('active');
      } else {
        return;
      }

    },

Solution

  • why not just check if e is an event or an element. then you could use it however you want.

    events: {
        'click .filter-options-container': 'filerOptionContainerClick',
    },
    //....
    filterOptionContainerClick: function( obj ) {
        if( !this.filtersEnabled || !obj ) {
            return;
        }
    
        if( obj.currentTarget ) {
            $( obj.currentTarget ).addClass( 'active' );
        } else if( $( obj ) && $( obj ).hasClass( 'filter-options-container' ) ) {
            $( obj ).addClass( 'active' );
        }
     }
    

    In other words, you could then just call filterOptionContainerClick manually. Something like:

     //.....
         this.filterOptionContainerClick( $( '.filter-options-container' ) );
     //....
    

    If you need to give each contain a unique identifier, you can either do this with an id attribute on the element, or just use a custom data-whatever attribute (i.e., <div class="filter-options-container" data-identifier='some unique id'>...</div> )